【问题标题】:Checking for empty or null List<string>检查空或 null List<string>
【发布时间】:2014-08-14 21:57:13
【问题描述】:

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

 // I have a list, sometimes it doesn't have any data added to it
    var myList = new List<object>(); 
 // 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"

【问题讨论】:

  • 请将您接受的答案更改为 L-Four 的答案,因为它比我的要好得多,而且这个问题似乎对许多人有用,因此请选择更好的答案。

标签: c# list


【解决方案1】:

试试下面的代码:

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

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

public static class IEnumerableExtension
{       
    public static IEnumerable<T> Safe<T>(this IEnumerable<T> 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"); 
 }

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

还有另一个 EDIT,它不需要扩展方法,但使用 ? (空条件)运算符(C# 6.0):

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

【讨论】:

  • 我们可以使用myList?.Count() &gt; 0 or myList?Length &gt; 0 or myList?.Any()?
  • Null-Conditional 使用需要固定为 if (!(myList?.Any() ?? false)) 以克服 Cannot implicitly convert type bool? to bool 错误
  • 比较if (!list?.Any() ?? false) {}(3个运算符)和if (list?.Any() != true) {}(2个运算符),我喜欢后者。
  • 如果myListnullmyList?.Any() 将返回null,因此myList?.Any() == false 不会成立。
【解决方案2】:

您可以通过多种方式检查列表是否为空

1)Checklist 为空,然后检查计数大于零,如下所示:-

if (myList != null && myList.Count > 0)
{
    //List has more than one record.
}

2) 使用 LINQ 查询的清单为空且计数大于零,如下所示:-

if (myList?.Any() == true)
{
    //List has more than one record.
}

【讨论】:

    【解决方案3】:

    您可以添加此 IEnumerable 扩展方法,如果源序列包含任何元素且不为 null,则该方法返回 true。否则返回 false。

    public static class IEnumerableExtensions
    {
        public static bool IsNotNullNorEmpty<T>(this IEnumerable<T> source)
           => source?.Any() ?? false;
    }
    

    【讨论】:

      【解决方案4】:

      我只是想在这里添加一个答案,因为这是 Google 检查列表是否为空或为空的热门话题。对我来说 .Any 无法识别。如果你想在不创建扩展方法的情况下进行检查,你可以这样做,这很简单:

      //Check that list is NOT null or empty.
      if (myList != null && myList.Count > 0)
      {
          //then proceed to do something, no issues here.
      }
      
      //Check if list is null or empty.
      if (myList == null || myList.Count == 0)
      {
          //error handling here for null or empty list
      }
      
      //checking with if/else-if/else
      if (myList == null)
      {
          //null handling
      }
      else if(myList.Count == 0)
      {
          //handle zero count
      }
      else
      {
          //no issues here, proceed
      }
      

      如果列表有可能为空,那么您必须首先检查是否为空 - 如果您尝试先检查计数并且列表恰好为空,那么它将引发错误。 &amp;&amp;|| 是短路运算符,因此仅在不满足第一个条件时才评估第二个条件。

      【讨论】:

        【解决方案5】:

        我个人为 IEnumerable 类创建了一个扩展方法,我称之为 IsNullOrEmpty()。因为它适用于 IEnumerable 的所有实现,所以它适用于 List,也适用于 String、IReadOnlyList 等。

        我的实现是这样的:

        public static class ExtensionMethods
        {
            public static bool IsNullOrEmpty(this IEnumerable enumerable)
            {
                if (enumerable is null) return true;
        
                foreach (var element in enumerable)
                {
                    //If we make it here, it means there are elements, and we return false
                    return false;
                }
        
                return true;
            }
        }
        

        然后我可以使用列表中的方法如下:

        var myList = new List<object>();
        
        if (myList.IsNullOrEmpty())
        {
            //Do stuff
        }
        

        【讨论】:

          【解决方案6】:

          这可以解决你的问题 `if(list.Length > 0){

          }`

          【讨论】:

            【解决方案7】:

            这里的大多数答案都集中在如何检查集合是空的还是空的,正如他们所展示的那样,这非常简单。

            和这里的许多人一样,我也想知道为什么微软自己不提供这样一个已经为 String 类型提供的基本功能(String.IsNullOrEmpty())?然后我遇到了这个guideline from Microsoft,上面写着:

            X 不要从集合属性或返回集合的方法返回空值。返回一个空集合或一个空数组。

            一般规则是 null 和空(0 项)集合或数组 应该同样对待。

            因此,理想情况下,如果您遵循 Microsoft 的此指南,则永远不应有一个为 null 的集合。这将帮助您消除不必要的空值检查,最终使您的代码更具可读性。在这种情况下,有人只需要检查:myList.Any() 以找出列表中是否存在任何元素。

            希望这个解释能帮助将来遇到同样问题并想知道为什么没有这样的功能来检查集合是否为空或空的人。

            【讨论】:

              【解决方案8】:

              组合myList == null || myList.Count == 0 的一种简单方法是使用空合并运算符??

              if ((myList?.Count ?? 0) == 0) {
                  //My list is null or empty
              }
              

              【讨论】:

              • 在我看来这是最好的答案。它避免了否定。
              【解决方案9】:

              我们可以添加一个扩展来创建一个空列表

                  public static IEnumerable<T> Nullable<T>(this IEnumerable<T> obj)
                  {
                      if (obj == null)
                          return new List<T>();
                      else
                          return obj;
                  }
              

              并像这样使用

              foreach (model in models.Nullable())
              {
                  ....
              }
              

              【讨论】:

                【解决方案10】:

                因为你用'new'初始化了myList,所以列表本身永远不会为空。

                但它可以用“空”值填充。

                在这种情况下,.Count &gt; 0.Any() 将是真的。您可以通过.All(s =&gt; s == null) 进行检查

                var myList = new List<object>();
                if (myList.Any() || myList.All(s => s == null))
                

                【讨论】:

                  【解决方案11】:

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

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

                  【讨论】:

                  • 改用(this IEnumerable&lt;T&gt;? source)
                  【解决方案12】:
                  if (myList?.Any() == true) 
                  {
                     ...
                  }
                  

                  我觉得这是最方便的方式。 '== true' 检查 '?.Any() 所隐含的可为空的布尔值

                  【讨论】:

                  • 对于任何感兴趣的人:==true 部分是必要的,因为myList?.Any() 的结果是bool? 的类型,if 语句无法正确检查。
                  【解决方案13】:

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

                  请在下面找到在一个条件下检查列表空和空的代码

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

                  【讨论】:

                  • 我不知道为什么这个答案不高,这是简单的老式方法。
                  【解决方案14】:

                  结帐L-Four's 回答。

                  效率较低的答案:

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

                  基本上new List&lt;T&gt; 不会是null,但不会有任何元素。如 cmets 中所述,如果列表未实例化,则上述内容将引发异常。但是对于问题中的sn-p,在哪里实例化,上面的就可以了。

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

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

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

                  【讨论】:

                  • 当列表为空时会抛出异常
                  • 不是好答案...如果您知道列表已实例化,请使用它
                  • 而不是myList.Count == 0 使用myList.Any(),它更常见、可读性更强。
                  • @SumitJoshi 效率也更高。 Count 将检查列表中的每个元素。
                  • @rmlarsen myList.Count 不会遍历列表。 List 在内部维护一个变量以保持其大小。就像读取属性一样。这是一个 O(1) 操作ref
                  【解决方案15】:

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

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

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

                  【讨论】:

                    【解决方案16】:

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

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

                    【讨论】:

                    • if (list?.Any().GetValueOrDefault()) - 可以是另一种消除否定比较的方法
                    • 你的意思是if (list?.Any()?.GetValueOrDefault())?是的,那将是另一种好方法。一目了然(至少对我来说)不太明显,但它是一个同样好的解决方案:)
                    • 是的,我尽量避免否定条件,如果可能的话,每次我看到!variable!= ;)
                    【解决方案17】:

                    我们可以使用扩展方法进行如下验证。我将它们用于我的所有项目。

                      var myList = new List<string>();
                      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"); 
                          }
                      }
                    
                    
                    
                    
                    /// <summary>
                    /// This Method will return True if List is Not Null and it's items count>0       
                    /// </summary>
                    /// <typeparam name="T"></typeparam>
                    /// <param name="items"></param>
                    /// <returns>Bool</returns>
                    public static bool HasValue<T>(this IEnumerable<T> items)
                    {
                        if (items != null)
                        {
                            if (items.Count() > 0)
                            {
                                return true;
                            }
                        }
                        return false;
                    }
                    
                    
                    /// <summary>
                    /// This Method will return True if List is Not Null and it's items count>0       
                    /// </summary>
                    /// <typeparam name="T"></typeparam>
                    /// <param name="items"></param>
                    /// <returns></returns>
                    public static bool HasValue<T>(this List<T> items)
                    {
                        if (items != null)
                        {
                            if (items.Count() > 0)
                            {
                                return true;
                            }
                        }
                        return false;
                    }
                    
                    
                    /// <summary>
                    ///  This method returns true if string not null and not empty  
                    /// </summary>
                    /// <param name="ObjectValue"></param>
                    /// <returns>bool</returns>
                    public static bool HasValue(this string ObjectValue)
                    {
                        if (ObjectValue != null)
                        {
                            if ((!string.IsNullOrEmpty(ObjectValue)) && (!string.IsNullOrWhiteSpace(ObjectValue)))
                            {
                                return true;
                            }
                        }
                        return false;
                    }
                    

                    【讨论】:

                      【解决方案18】:

                      试用并使用:

                      if(myList.Any())
                      {
                      
                      }
                      

                      注意:这里假定 myList 不为空。

                      【讨论】:

                      • 这会在列表为空时抛出异常
                      • 返回真; // 这假定列表不为 null 或为空
                      【解决方案19】:

                      使用扩展方法怎么样?

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

                      【讨论】:

                      • 我想知道为什么没有内置这样的东西,就像 String.IsNullOrEmpty(string str)
                      • 为什么不只是return source != null &amp;&amp; source.Any();
                      • 您的方法名称是AnyOrNotNull,但您的比较是AND,我认为正确的名称是AnyAndNotNull
                      【解决方案20】:

                      假设列表永远不会为空,下面的代码会检查列表是否为空,如果为空则添加一个新元素:

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

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

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

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

                      【讨论】:

                      • 我真的很想对此投赞成票,但空检查应该是:if (myList == null || !myList.Any())
                      • @BATabNabber:实际上是非空检查。如果 myList 为 null,我们不能向其中添加任何项目。另请参阅 L-4 的答案。
                      【解决方案21】:

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

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

                      【讨论】:

                        【解决方案22】:

                        您的列表没有项目,这就是为什么访问不存在的第 0 个项目

                        myList[0] == null
                        

                        抛出索引超出范围异常;当你想访问 n-th 项目检查时

                          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");
                        

                        【讨论】:

                          【解决方案23】:

                          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
                          

                          【讨论】:

                            猜你喜欢
                            • 2021-11-30
                            • 2022-01-09
                            • 2014-07-26
                            • 2019-11-27
                            • 1970-01-01
                            • 1970-01-01
                            • 2013-03-14
                            • 1970-01-01
                            • 1970-01-01
                            相关资源
                            最近更新 更多