【发布时间】:2016-08-04 08:49:20
【问题描述】:
我在很多代码sn-ps中看到,下面这个条件是用来检查一个列表是否为空的:
List<string> someList = someFunctionThatPopulatesAList();
if (someList == null || someList.Count <= 0)
return;
我想知道 - 为什么不使用以下条件:
if (someList == null || someList.Count == 0)
return;
有没有List<T>.Count为负数的情况?
【问题讨论】:
-
不,没有。你说的对。没有必要使用
<= -
或者更好的List
.Any() -
我从未见过使用
someList.Count <= 0的代码,我同意这毫无意义。 -
@Negorath - 不,它没有。
Count定义为O(1)操作。无需迭代即可获得。
标签: c# .net list comparison-operators empty-list