检查空或空List

我有一个List,有时它是空的或null。 我希望能够检查它是否包含任何List项,如果没有,则将对象添加到List。

// I have a list, sometimes it doesn't have any data added to it var myList = new List(); // Expression is always false if (myList == null) Console.WriteLine("List is never null"); if (myList[0] == null) myList.Add("new item"); //Errors encountered: Index was out of range. Must be non-negative and less than the size of the collection. // Inner Exception says "null" 

请尝试以下代码:

  if ( (myList!= null) && (!myList.Any()) ) { // Add new item myList.Add("new item"); } 

编辑迟到,因为对于这些检查我现在想使用以下解决方案。 首先,添加一个名为Safe()的小型可重用扩展方法:

 public static class IEnumerableExtension { public static IEnumerable Safe(this IEnumerable source) { if (source == null) { yield break; } foreach (var item in source) { yield return item; } } } 

然后,你可以这样做:

  if (!myList.Safe().Any()) { // Add new item myList.Add("new item"); } 

我个人认为这不那么冗长,也更容易阅读。 您现在可以安全地访问任何集合,而无需进行空检查。

对于没有保证列表为null的任何人,您可以使用空条件运算符在单个条件语句中安全地检查空列表和空列表:

 if (list?.Any() != true) { // Handle null or empty list } 

结帐L-Four的答案。

一个效率较低的答案:

 if(myList.Count == 0){ // nothing is there. Add here } 

基本上new List不会为null但没有元素。 正如评论中所指出的,如果列表未实例化,上述内容将抛出exception。 但至于问题中的片段,它被实例化,上面的工作就好了。

如果你需要检查null,那么它将是:

 if(myList != null && myList.Count == 0){ // The list is empty. Add something here } 

更好的是使用!myList.Any()并且正如前面提到的L-Four的答案中提到的那样,短路比列表中元素的线性计数更快。

那么使用扩展方法呢?

 public static bool AnyOrNotNull(this IEnumerable source) { if (source != null && source.Any()) return true; else return false; } 

假设列表永远不为null,以下代码检查列表是否为空,如果为空则添加新元素:

 if (!myList.Any()) { myList.Add("new item"); } 

如果列表可能为null,则必须在Any()条件之前添加空检查:

 if (myList != null && !myList.Any()) { myList.Add("new item"); } 

在我看来,使用Any()而不是Count == 0是首选,因为它更好地表达了检查列表是否有任何元素或为空的意图。 但是,考虑到每种方法的性能,使用Any()通常比Count 慢 。

您的列表没有项目 ,这就是访问不存在的第0项的原因

 myList[0] == null 

抛出指数超出范围exception ; 当你想要访问第n项检查

  if (myList.Count > n) DoSomething(myList[n]) 

在你的情况下

  if (myList.Count > 0) // <- You can safely get 0-th item if (myList[0] == null) myList.Add("new item"); 

如果你想要一个同时检查null和empty的单行条件,你可以使用

 if (list == null ? true : (!list.Any())) 

这将适用于旧条件运算符不可用的旧框架版本。

c#中的List具有Count属性。 它可以像这样使用:

 if(myList == null) // Checks if list is null // Wasn't initialized else if(myList.Count == 0) // Checks if the list is empty myList.Add("new item"); else // List is valid and has something in it // You could access the element in the list if you wanted 

myList[0]获取列表中的第一项。 由于列表为空,因此没有要获取的项目,而是获得IndexOutOfRangeException

正如其他答案所示,为了检查列表是否为空,您需要获取列表中的元素数量( myList.Count )或使用LINQ方法myList.Count .Any()如果有任何元素将返回true在列表中。

尝试并使用:

 if(myList.Any()) { } 

注意:这个assmumes myList不为null。

我想知道没有人建议为OP的案例创建自己的扩展方法更可读的名称。

 public static bool IsNullOrEmpty(this IEnumerable source) { if (source == null) { return true; } return source.Any() == false; } 

我们可以使用Extension方法进行如下validation。 我将它们用于我的所有项目。

  var myList = new List(); if(!myList.HasValue()) { Console.WriteLine("List has value(s)"); } if(!myList.HasValue()) { Console.WriteLine("List is either null or empty"); } if(myList.HasValue()) { if (!myList[0].HasValue()) { myList.Add("new item"); } } ///  /// This Method will return True if List is Not Null and it's items count>0 ///  ///  ///  /// Bool public static bool HasValue(this IEnumerable items) { if (items != null) { if (items.Count() > 0) { return true; } } return false; } ///  /// This Method will return True if List is Not Null and it's items count>0 ///  ///  ///  ///  public static bool HasValue(this List items) { if (items != null) { if (items.Count() > 0) { return true; } } return false; } ///  /// This method returns true if string not null and not empty ///  ///  /// bool public static bool HasValue(this string ObjectValue) { if (ObjectValue != null) { if ((!string.IsNullOrEmpty(ObjectValue)) && (!string.IsNullOrWhiteSpace(ObjectValue))) { return true; } } return false; } 

你可以在c#中使用List的Count属性

请查找以下代码,在单个条件下检查列表为空和null

 if(myList == null || myList.Count == 0) { //Do Something } 
 if (myList?.Any() == true) { ... } 

我发现这是最方便的方式。 ‘== true’检查’?。隐藏的可空的bool的值。?.Any()