如何检查 IEnumerable 是否为 null 或为空?
我喜欢 string.IsNullOrEmpty 方法。我希望有一些东西可以为 IEnumerable 提供相同的功能。有这样的吗?也许是一些集合助手类?我问的原因是,在 if
语句中,如果模式是 (mylist != null && mylist.Any())
,代码看起来会很混乱。使用 Foo.IsAny(myList)
会更干净。
这篇文章没有给出这个答案:IEnumerable 是空的?。
I love string.IsNullOrEmpty
method. I'd love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection helper class? The reason I am asking is that in if
statements the code looks cluttered if the patter is (mylist != null && mylist.Any())
. It would be much cleaner to have Foo.IsAny(myList)
.
This post doesn't give that answer: IEnumerable is empty?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
当然,您可以这样写:
但是,请注意并非所有序列都是可重复的; 通常我宁愿只走一次,以防万一。
Sure you could write that:
however, be cautious that not all sequences are repeatable; generally I prefer to only walk them once, just in case.
这是 @Matt Greer 的有用答案的修改版本,其中包含一个静态包装类,因此您只需将其复制粘贴到新的源文件中,不依赖于 Linq,并添加一个通用的
IEnumerable重载,以避免非泛型版本中发生的值类型装箱。 [编辑:请注意,使用
IEnumerable
不会阻止枚举器装箱,鸭子类型 无法阻止这种情况,但至少值类型集合中的元素不会被装箱。]Here's a modified version of @Matt Greer's useful answer that includes a static wrapper class so you can just copy-paste this into a new source file, doesn't depend on Linq, and adds a generic
IEnumerable<T>
overload, to avoid the boxing of value types that would occur with the non-generic version. [EDIT: Note that use ofIEnumerable<T>
does not prevent boxing of the enumerator, duck-typing can't prevent that, but at least the elements in a value-typed collection will not each be boxed.]另一种方法是获取 Enumerator 并调用 MoveNext() 方法来查看是否有任何项目:
这适用于 IEnumerable 以及 IEnumerable。
Another way would be to get the Enumerator and call the MoveNext() method to see if there are any items:
This works for IEnumerable as well as IEnumerable<T>.
我这样做的方式是利用一些现代 C# 功能:
选项 1)
选项 2)
顺便说一下,永远不要使用
Count == 0
或Count() == 0
code> 只是检查集合是否为空。始终使用 Linq 的.Any()
The way I do it, taking advantage of some modern C# features:
Option 1)
Option 2)
And by the way, never use
Count == 0
orCount() == 0
just to check if a collection is empty. Always use Linq's.Any()
从 C#6 开始,您可以使用 空传播< /a>:
myList?.Any() == true
如果您仍然觉得这太堵塞或者更喜欢好的 ol' 扩展方法,我会推荐 Matt Greer 和 Marc Gravell 的答案,但有一点扩展功能的完整性。
他们的答案提供了相同的基本功能,但各自从不同的角度来看。马特的答案使用
string.IsNullOrEmpty
-心态,而 Marc 的答案则采用 Linq 的.Any()
方式来完成工作。我个人倾向于使用
。 Any()
道路,但希望从该方法的 其他重载:因此您仍然可以执行以下操作:
myList.AnyNotNull(item=>item.AnswerToLife == 42);
就像使用常规.Any()
一样,但添加了 null 检查请注意,使用C#6方式:
myList?.Any()
返回的是bool?
而不是bool
,这是的实际效果传播 nullStarting with C#6 you can use null propagation:
myList?.Any() == true
If you still find this too cloggy or prefer a good ol' extension method, I would recommend Matt Greer and Marc Gravell's answers, yet with a bit of extended functionality for completeness.
Their answers provide the same basic functionality, but each from another perspective. Matt's answer uses the
string.IsNullOrEmpty
-mentality, whereas Marc's answer takes Linq's.Any()
road to get the job done.I am personally inclined to use the
.Any()
road, but would like to add the condition checking functionality from the method's other overload:So you can still do things like :
myList.AnyNotNull(item=>item.AnswerToLife == 42);
as you could with the regular.Any()
but with the added null checkNote that with the C#6 way:
myList?.Any()
returns abool?
rather than abool
, which is the actual effect of propagating null这可能有帮助
This may help
当涉及引用(可为空)类型并且项目中不存在空项目时,可以使用这一行进行验证
One can use this line for that verification when it's about reference (nullable) types and when no null item expected among the items
Jon Skeet 的 anwser (https://stackoverflow.com/a/28904021/8207463) 有一个使用扩展方法的好方法 - Any() 表示 NULL 和 EMPTY。但他正在验证问题的所有者以防 NOT NULL。
因此,请小心地将 Jon 验证 AS NULL 的方法更改为:
请勿使用(不会验证 AS NULL):
您还可以在验证 AS NOT NULL 的情况下(未作为示例进行测试,但没有编译器错误)执行类似于使用谓词的操作:
https://referencesource.microsoft.com/#System。 Core/System/Linq/Enumerable.cs,8788153112b7ffd0
对于您可以使用的 .NET 版本,请检查:
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable .any?view=netframework-4.8#moniker-applies-to
Jon Skeet's anwser (https://stackoverflow.com/a/28904021/8207463) has a good approach using Extension Method - Any() for NULL and EMPTY. BUT he´s validating the questions´owner in case for NOT NULL.
So carefully change Jon´s approach to validate AS NULL to:
DO NOT use ( will not validate AS NULL):
You can also in case validating AS NOT NULL ( NOT tested just as example but without compiler error) do something like using predicate :
https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0
For which .NET version you can use it please check:
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-4.8#moniker-applies-to
以下是 Marc Gravell 的回答中的代码,以及使用它的示例。
正如他所说,并非所有序列都是可重复的,因此代码有时可能会导致问题,因为
IsAny()
开始逐步执行序列。我怀疑 Robert Harvey 的回答 的意思是您通常不需要检查null
和空。通常,您可以只检查 null,然后使用foreach
。为了避免启动序列两次并利用
foreach
,我只编写了一些如下代码:我猜扩展方法可以为您节省几行输入,但这段代码对我来说似乎更清晰。我怀疑一些开发人员不会立即意识到
IsAny(items)
实际上会开始逐步执行该序列。 (当然,如果您使用大量序列,您很快就会学会思考其中的步骤。)Here's the code from Marc Gravell's answer, along with an example of using it.
As he says, not all sequences are repeatable, so that code may sometimes cause problems, because
IsAny()
starts stepping through the sequence. I suspect what Robert Harvey's answer meant was that you often don't need to check fornull
and empty. Often, you can just check for null and then useforeach
.To avoid starting the sequence twice and take advantage of
foreach
, I just wrote some code like this:I guess the extension method saves you a couple of lines of typing, but this code seems clearer to me. I suspect that some developers wouldn't immediately realize that
IsAny(items)
will actually start stepping through the sequence. (Of course if you're using a lot of sequences, you quickly learn to think about what steps through them.)我使用
Bool IsCollectionNullOrEmpty = !(Collection?.Any()??false);
。希望这有帮助。细分:
如果 Collection 为 null,则
Collection?.Any()
将返回null
;如果 Collection 为空,则返回false
。如果 Collection 为空,
Collection?.Any()??false
将为我们提供false
;如果 Collection 为null
,则为false
代码>.对此的补充将为我们提供
IsEmptyOrNull
。I use
Bool IsCollectionNullOrEmpty = !(Collection?.Any()??false);
. Hope this helps.Breakdown:
Collection?.Any()
will returnnull
if Collection is null, andfalse
if Collection is empty.Collection?.Any()??false
will give usfalse
if Collection is empty, andfalse
if Collection isnull
.Complement of that will give us
IsEmptyOrNull
.我遇到了同样的问题,我解决它的方式如下:
“c=>c!=null”将忽略所有空实体。
I had the same problem and I solve it like :
"c=>c!=null" will ignore all the null entities.
我是根据@Matt Greer的回答构建的,
他完美地回答了OP的问题。
我想要这样的东西,同时保持 Any 的原始功能,同时检查 null 。我发布这个以防其他人需要类似的东西。
具体来说,我希望仍然能够传递谓词。
扩展方法的命名可能会更好。
I built this off of the answer by @Matt Greer
He answered the OP's question perfectly.
I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.
Specifically I wanted to still be able to pass in a predicate.
The naming of the extension method could probably be better.
只需添加
using System.Linq
并在您尝试访问IEnumerable
中的可用方法时看到奇迹发生。添加它将使您能够访问名为Count()
的方法,就这么简单。只需记住在调用count()
之前检查null 值
:)just add
using System.Linq
and see the magic happening when you try to access the available methods in theIEnumerable
. Adding this will give you access to method namedCount()
as simple as that. just remember to check fornull value
before callingcount()
:)我使用简单的 if 来检查它,
看看我的解决方案
I used simple if to check for it
check out my solution
下面的另一个最佳解决方案来检查是否为空?
The other best solution as below to check empty or not ?
我用的是这个:
Ejem:
I use this one:
Ejem:
由于有些资源读完就耗尽了,我想为什么不把检查和读结合起来,而不是传统的单独检查,然后读。
首先,我们有一个更简单的 check-for-null 内联扩展:
然后我们有更多的参与(嗯,至少是我编写的方式) check-for-null-and-empty 内联扩展:
你当然仍然可以调用两者而不继续调用链。另外,我还包含了 paramName,以便调用者可以在未检查“源”的情况下包含错误的备用名称,例如“nameof(target)”。
Since some resources are exhausted after one read, I thought why not combine the checks and the reads, instead of the traditional separate check, then read.
First we have one for the simpler check-for-null inline extension:
Then we have the little more involved (well, at least the way I wrote it) check-for-null-and-empty inline extension:
You can of course still call both without continuing the call chain. Also, I included the paramName, so that the caller may include an alternate name for the error if it's not "source" being checked, e.g. "nameof(target)".
我自己的扩展方法来检查 Not null 和 Any
my own extension method to check Not null and Any
如果没有自定义助手,我推荐
?.Any() ?? false
或?.Any() == true
比较简洁,只需要指定一次序列。当我想将丢失的集合视为空集合时,我使用以下扩展方法:
此函数可以与所有 LINQ 方法和
foreach
结合使用,而不仅仅是.Any(),这就是为什么我更喜欢它而不是人们在这里提出的更专业的帮助函数。
Without custom helpers I recommend either
?.Any() ?? false
or?.Any() == true
which are relatively concise and only need to specify the sequence once.When I want to treat a missing collection like an empty one, I use the following extension method:
This function can be combined with all LINQ methods and
foreach
, not just.Any()
, which is why I prefer it over the more specialized helper functions people are proposing here.我使用
如果不匹配,结果将为 null,否则返回对象之一
如果您想要列表,我相信离开 First() 或调用 ToList() 将提供列表或 null。
I use
The result will be null if no match, otherwise returns one of the objects
If you wanted the list, I believe leaving of First() or calling ToList() will provide the list or null.
it null 将
在此处返回 true 代码
it null will return true
code here