我喜欢绳子。IsNullOrEmpty方法。我想有一些东西,将允许相同的功能IEnumerable。有这样的东西吗?也许是一些收集助手类?我问的原因是,在if语句中,如果模式是(mylist != null && mylist. any()),代码看起来很混乱。使用Foo.IsAny(myList)会干净得多。
这篇文章没有给出答案:IEnumerable是空的?
我喜欢绳子。IsNullOrEmpty方法。我想有一些东西,将允许相同的功能IEnumerable。有这样的东西吗?也许是一些收集助手类?我问的原因是,在if语句中,如果模式是(mylist != null && mylist. any()),代码看起来很混乱。使用Foo.IsAny(myList)会干净得多。
这篇文章没有给出答案:IEnumerable是空的?
当前回答
我用简单的if来检查它
看看我的解决方案
foreach (Pet pet in v.Pets)
{
if (pet == null)
{
Console.WriteLine(" No pet");// enumerator is empty
break;
}
Console.WriteLine(" {0}", pet.Name);
}
其他回答
我用简单的if来检查它
看看我的解决方案
foreach (Pet pet in v.Pets)
{
if (pet == null)
{
Console.WriteLine(" No pet");// enumerator is empty
break;
}
Console.WriteLine(" {0}", pet.Name);
}
我使用Bool IsCollectionNullOrEmpty = !(Collection?. any ()??false);。希望这能有所帮助。
分解:
. any()如果Collection为空将返回null,如果Collection为空则返回false。
收集? .Any () ?如果Collection为空,则返回false;如果Collection为空,则返回false。
它的补将得到IsEmptyOrNull。
Jon Skeet的回答(https://stackoverflow.com/a/28904021/8207463)有一个很好的方法,使用扩展方法- Any()为NULL和EMPTY。但是他正在验证问题的所有者,以防NOT NULL。 因此,请仔细更改Jon验证AS NULL的方法为:
If (yourList?.Any() != true)
{
..your code...
}
不使用(将不验证为NULL):
If (yourList?.Any() == false)
{
..your code...
}
你也可以在验证AS NOT NULL的情况下(没有测试,只是作为例子,但没有编译器错误)做一些类似使用predicate的事情:
If (yourList?.Any(p => p.anyItem == null) == true)
{
..your code...
}
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
另一种方法是获取枚举器并调用MoveNext()方法来查看是否有任何项:
if (mylist != null && mylist.GetEnumerator().MoveNext())
{
// The list is not null or empty
}
这适用于IEnumerable和IEnumerable<T>。
if (collection?.Any() == true){
// if collection contains more than one item
}
if (collection?.Any() != true){
// if collection is null
// if collection does not contain any item
}