C# 如何检查列表是否为空

200

我有一个通用列表对象。我需要检查这个列表是否为空。

在C#中,如何检查List<T>是否为空?


12
使用 if (list.Count == 0) { /* ... */ } 有什么问题? - Bart van Nierop
16
如果列表为空,就执行 if (!list.Any()) - Tharwen
2
这个:https://dev59.com/OWoy5IYBdhLWcg3wZdKr - CAD bloke
8个回答

209
你可以使用 Enumerable.Any:
bool isEmpty = !list.Any();
if(isEmpty)
{
    // ...
}  

如果列表可能为 null,那么您可以使用:

bool isNullOrEmpty = list?.Any() != true;

4
首先检查 list == null 不是最好的方法吗? - ᴍᴀᴛᴛ ʙᴀᴋᴇʀ
6
@ᴍᴀᴛᴛʙᴀᴋᴇʀ,var someList = new List<string>(); 将被实例化(因此不会为null),但将不包含任何要处理的元素。 - daviesdoesit

104

如果您正在使用的列表实现是 IEnumerable<T>,并且 Linq 是一种选择,您可以使用 Any

if (!list.Any()) {

}

否则,通常在数组和集合类型上有一个LengthCount属性。


20
一个快速的提示:list.Any 的性能比 count 好得多。 - Adrian Lopez
3
@AdrianLopez:你能详细说明一下吗?如果你有一个类似于List.Count.Length属性,那么.Any()可能怎么比检查该集合的长度或计数属性更快呢?如果你只有一个枚举器,那么.Any()当然比.Count() > 0快。参见:https://dev59.com/g3VC5IYBdhLWcg3wZwTj或https://dev59.com/PW025IYBdhLWcg3w4qEx?noredirect=1&lq=1 - noox
3
在查看 (.Net Core) 源代码时,似乎 Any 方法在测试计数值前会检查检索计数值是否廉价。如果你有一个不跟踪计数值的 IListProvider<>,它将枚举一次而不是多次。 - NetMage

42
    If (list.Count==0){
      //you can show your error messages here
    } else {
      //here comes your datagridview databind 
    }

您可以将数据网格的可见性设置为 false,并在 else 部分将其设置为可见。


1
@NetMage,对于列表来说,它的工作方式并不是这样的。它是一种O(1)操作,并且在计算元素数量时没有进行迭代。请参见List<T>.Count - Spencer Wieczorek
2
@SpencerWieczorek 您是正确的,那个评论既过时又错误 :) 尽管一般而言,我仍然更喜欢使用 Any() 来更好地表达意图,并且在您不知道是否有实际的 List<T> 时性能更佳。 - NetMage

26

那么使用 Count 属性怎么样呢?

 if(listOfObjects.Count != 0)
 {
     ShowGrid();
     HideError();
 }
 else
 {
     HideGrid();
     ShowError();
 }

4
"Count" 是一个属性而不是一个方法。 - Moslem Ben Dhaou
6
这取决于调用的是暴露/公开的Linq扩展方法,还是对象本身自带的。 - Grant Thomas
1
@GrantThomas 我把它当作了一个List<T>对象,但是你说得对。 - Moslem Ben Dhaou
1
如果listOfObjects为空怎么办? - Sabri Meviş
3
从一个方法返回的集合/可枚举对象/列表不应该为 null,而应该是一个空的集合。 - Jeroen van Langen

11

你应该使用简单的IF语句。

List<String> data = GetData();

if (data.Count == 0)
    throw new Exception("Data Empty!");

PopulateGrid();
ShowGrid();

在我看来,最简单和最好的方法。 - Jabba
1
如果该方法返回空值,Count属性将会失败。 为了使代码简洁,考虑使用空引用检查运算符“?”。 例如:“if (data?.Count == 0)……” 或者使用经典的空值检查:“if (data != null && someOtherCondition) ……” - daviesdoesit
将以下代码粘贴到 dotnetfiddle 中,您将看到 System.NullReferenceException: Object reference not set to an instance of an object.`using System; using System.Collections.Generic;public class Program { public static void Main() { List<string> stringList = null; if (stringList.Count == 0) { Console.WriteLine("no items in collection"); } } } ` - daviesdoesit
@daviesdoesit,这超出了问题的范围。这段代码明显假定data已经被定义。 - Moslem Ben Dhaou

8
var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source

4

GridView本身有一个方法,可以检查您要绑定到它的数据源是否为空,它允许您显示其他内容。


1
如果您正在使用GridView,则请使用空数据模板:http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        runat="server">

        <emptydatarowstyle backcolor="LightBlue"
          forecolor="Red"/>

        <emptydatatemplate>

          <asp:image id="NoDataImage"
            imageurl="~/images/Image.jpg"
            alternatetext="No Image" 
            runat="server"/>

            No Data Found.  

        </emptydatatemplate> 

      </asp:gridview>

这非常特定于ASP.NET。 - Grant Thomas
我不是WinForms的专家,但GridView不是ASP.NET特有的吗?在Forms中应该是DataGridView吧? - David MacCrimmon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接