非空List对象的Count是否总是大于0?

问题描述 投票:0回答:3

在 C# 中,如果

List()
对象不为 null,是否也意味着
Count
始终大于 0?

例如,如果您有一个类型为

intList
的对象
List<int>
,那么以下代码是否多余?

if (intList != null && intList.Count > 0) {
    // do something
}
c# .net list
3个回答
11
投票

不,有一个空列表是完全有效的:

List<int> intList = new List<int>();
bool isEmpty = intList.Count == 0; // true
        

如果您想知道列表是否不为空并且至少包含一项,您还可以使用 C#6 null 条件运算符:

List<int> intList = null;
bool isNotEmpty = intList?.Count > 0; // no exception, false
        

1
投票

不,该代码并不多余。

intList
可以为 null 或
intList.Count == 0
。 以下是一些案例:

List<int> intList = null;

Console.WriteLine(intList);  // it will print 'null'

intList = new List<int>();

Console.WriteLine(intList.Count); // it will print '0'

在现代 C# 中,您可以使用 Null 条件运算符 来简化检查。 这个语法在性能上相当于测试

null
,它只是一个语法糖来简化这个常见的检查。

if (intList?.Count > 0) {
    // do something
}

1
投票

以上所有答案都是自我解释的。 尝试添加更多一点

if (intList != null && intList.Count > 0) 这里检查计数以确保 intList 中至少有一项,然后再对列表执行任何操作。 除了空检查之外,我们检查计数的最常见用例是当我们想要迭代列表的项目时。

if (intList != null && intList.Count > 0) 
{
    foreach(var item in intList)
    {
        //Do something with item.
    }
}

如果列表为空,则尝试迭代它是没有意义的。

但是如果 intList 不为 null,并不意味着它的 count > 0。如果 count 必须大于零,则需要将项目添加到列表中。

© www.soinside.com 2019 - 2024. All rights reserved.