C# 如何检查IEnumerable是否为null或空?

C# 如何检查IEnumerable是否为null或空?,c#,.net,linq,collections,ienumerable,C#,.net,Linq,Collections,Ienumerable,我喜欢string.IsNullOrEmpty方法。我希望有一些东西可以让IEnumerable具有相同的功能。有这样的情况吗?也许是一些收集助手类?我询问的原因是,在if语句中,如果模式是(mylist!=null&&mylist.Any()),则代码看起来很混乱。如果有Foo.IsAny(myList),会更干净 这篇文章没有给出答案:。公共静态bool为空或空(此IEnumerable可枚举){ 返回enumerable==null | |!enumerable.Any(); } 你肯定可

我喜欢
string.IsNullOrEmpty
方法。我希望有一些东西可以让IEnumerable具有相同的功能。有这样的情况吗?也许是一些收集助手类?我询问的原因是,在
if
语句中,如果模式是
(mylist!=null&&mylist.Any())
,则代码看起来很混乱。如果有
Foo.IsAny(myList)
,会更干净

这篇文章没有给出答案:。

公共静态bool为空或空(此IEnumerable可枚举){
返回enumerable==null | |!enumerable.Any();
}

你肯定可以写下:

public static class Utils {
    public static bool IsAny<T>(this IEnumerable<T> data) {
        return data != null && data.Any();
    }
}
公共静态类Utils{
公共静态bool IsAny(此IEnumerable数据){
返回数据!=null&&data.Any();
}
}
但是,要注意,并非所有序列都是可重复的;一般来说,我只喜欢走一次,以防万一。

这是来自的代码,以及使用它的示例

using System;
using System.Collections.Generic;
using System.Linq;

public static class Utils
{
    public static bool IsAny<T>(this IEnumerable<T> data)
    {
        return data != null && data.Any();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        if (items.IsAny())
        {
            foreach (var item in items)
            {
                Console.WriteLine(item);
            }
        }
        else
        {
            Console.WriteLine("No items.");
        }
    }
}

我想扩展方法可以节省几行输入,但我觉得这段代码更清晰。我怀疑一些开发人员不会立即意识到,
IsAny(items)
实际上会开始逐步执行序列。(当然,如果你使用了大量的序列,你很快就会学会思考通过它们的步骤。)

这里是@Matt Greer有用答案的一个修改版本,其中包括一个静态包装类,因此你可以将其复制粘贴到一个新的源文件中,不依赖Linq,并添加一个通用的
IEnumerable
重载,避免非泛型版本可能出现的值类型装箱。[编辑:请注意,使用
IEnumerable
不会阻止枚举数装箱,也不能阻止装箱,但至少值类型集合中的元素不会每个都装箱。]

using System.Collections;
using System.Collections.Generic;

public static class IsNullOrEmptyExtension
{
    public static bool IsNullOrEmpty(this IEnumerable source)
    {
        if (source != null)
        {
            foreach (object obj in source)
            {
                return false;
            }
        }
        return true;
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
    {
        if (source != null)
        {
            foreach (T obj in source)
            {
                return false;
            }
        }
        return true;
    }
}
使用系统集合;
使用System.Collections.Generic;
公共静态类为NullOrEmptyExtension
{
公共静态bool为空(此IEnumerable源)
{
如果(源!=null)
{
foreach(源中的对象obj)
{
返回false;
}
}
返回true;
}
公共静态bool为空(此IEnumerable源)
{
如果(源!=null)
{
foreach(源中的目标)
{
返回false;
}
}
返回true;
}
}

另一种方法是获取枚举数并调用MoveNext()方法以查看是否有任何项:

if (mylist != null && mylist.GetEnumerator().MoveNext())
{
    // The list is not null or empty
}

这适用于IEnumerable和IEnumerable。

只需使用System.Linq添加
,当您尝试访问
IEnumerable
中的可用方法时,就会看到神奇的效果。添加它将使您能够访问名为
Count()
的方法,就这么简单。在调用
count()
:)

之前,请记住检查
null值,以我的方式,利用一些现代C#功能:

备选方案1)

公共静态类Utils{
公共静态bool为空(此IEnumerable列表){
return!(list?Any()?false);
}
}
备选方案2)

公共静态类Utils{
公共静态bool为空(此IEnumerable列表){
return!(list?.Any()).GetValueOrDefault();
}
}

顺便说一句,不要仅仅使用
Count==0
Count()==0
来检查集合是否为空。总是使用Linq的
.Any()

我用simple if检查它

查看我的解决方案

foreach (Pet pet in v.Pets)
{
    if (pet == null)
    {
        Console.WriteLine(" No pet");// enumerator is empty
        break;
    }
    Console.WriteLine("  {0}", pet.Name);
}
从C#6开始,您可以使用:
myList?.Any()==true

如果你仍然觉得这太麻烦或者更喜欢一个好的ol'扩展方法,我会推荐Matt Greer和Marc Gravell的答案,但是为了完整性,有一点扩展功能

他们的答案提供了相同的基本功能,但每个都从另一个角度出发。马特的回答采用了-思维,而马克的回答采用了林克的
.Any()
方法来完成工作

我个人倾向于使用道路,但我想从该方法的以下功能中添加条件检查功能:

public static bool AnyNotNull(此IEnumerable源,Func谓词=null)
{
if(source==null)返回false;
返回谓词==null
?来源:Any()
:source.Any(谓词);
}
因此,您仍然可以执行以下操作:
myList.AnyNotNull(item=>item.AnswerToLife==42)
与常规的
.Any()
一样,但添加了空检查

注意,使用C#6方式:
myList?.Any()
返回一个
bool?
,而不是
bool
,这是传播null的实际效果

他完美地回答了OP的问题

我想要这样的东西,同时保持Any的原始功能,同时检查null。我把这个贴出来,以防其他人需要类似的东西

具体来说,我希望仍然能够传入谓词

公共静态类实用程序
{
/// 
///确定序列是否具有值并包含任何元素。
/// 
///源的元素的类型。
///检查是否有空。
///如果源序列不为null且包含任何元素,则为true;否则为false。
公共静态bool AnyNotNull(此IEnumerable源)
{
返回源?.Any()==true;
}
/// 
///确定序列是否具有值以及序列的任何元素是否满足条件。
/// 
///源的元素的类型。
///要对其应用谓词的元素的。
///测试每个元素的条件的函数。
///如果源序列不为null,并且源序列中的任何元素都通过了指定谓词中的测试,则为true;或者
if (mylist != null && mylist.GetEnumerator().MoveNext())
{
    // The list is not null or empty
}
public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any() ?? false);
    }
}
public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any()).GetValueOrDefault();
    }
}
foreach (Pet pet in v.Pets)
{
    if (pet == null)
    {
        Console.WriteLine(" No pet");// enumerator is empty
        break;
    }
    Console.WriteLine("  {0}", pet.Name);
}
    public static bool AnyNotNull<T>(this IEnumerable<T> source, Func<T, bool> predicate = null)
    {
        if (source == null) return false;
        return predicate == null
            ? source.Any()
            : source.Any(predicate);
    }
public static bool IsAny<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() == true;
}

public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() != true;
}
    public bool HasMember(IEnumerable<TEntity> Dataset)
    {
        return Dataset != null && Dataset.Any(c=>c!=null);
    }
for(var item in listEnumerable)
{
 var count=item.Length;
  if(count>0)
  {
         // not empty or null
   }
  else
  {
       // empty
  }
}
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
}
    public static bool IsNotEmpty(this ICollection elements)
    {
        return elements != null && elements.Count > 0;
    }
List<string> Things = null;
if (Things.IsNotEmpty())
{
    //replaces ->  if (Things != null && Things.Count > 0) 
}
public static System.Collections.Generic.IEnumerable<T> ThrowOnNull<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null) => source ?? throw new System.ArgumentNullException(paramName ?? nameof(source));

var first = source.ThrowOnNull().First();
public static System.Collections.Generic.IEnumerable<T> ThrowOnNullOrEmpty<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null)
{
  using (var e = source.ThrowOnNull(paramName).GetEnumerator())
  {
    if (!e.MoveNext())
    {
      throw new System.ArgumentException(@"The sequence is empty.", paramName ?? nameof(source));
    }

    do
    {
      yield return e.Current;
    }
    while (e.MoveNext());
  }
}

var first = source.ThrowOnNullOrEmpty().First();
 public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source != null && source.Any();
    }
public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
{
    return sequence ?? Enumerable.Empty<T>();
}
If (yourList?.Any() != true) 
{
     ..your code...
}
If (yourList?.Any() == false) 
{
     ..your code...
}
If (yourList?.Any(p => p.anyItem == null) == true) 
{
     ..your code...
}
    list.Where (r=>r.value == value).DefaultIfEmpty().First()
public static bool IsEmpty(this System.Collections.IEnumerable enumerable)