相关疑难解决方法(0)

哪种方法表现更好:.Any()vs .Count()> 0?

System.Linq命名空间,我们现在可以扩展我们IEnumerable的有Any()Count() 扩展方法.

最近我被告知如果我想检查一个集合中是否包含一个或多个项目,我应该使用.Any()扩展方法而不是.Count() > 0扩展方法,因为.Count()扩展方法必须迭代所有项目.

其次,一些集合具有属性(未扩展方法),其是CountLength.使用它们会更好吗,而不是.Any().Count()

是啊/是?

.net linq performance extension-methods .net-3.5

555
推荐指数
6
解决办法
14万
查看次数

检查空或空List <string>

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

 // 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"
Run Code Online (Sandbox Code Playgroud)

c# list

47
推荐指数
9
解决办法
20万
查看次数

标签 统计

.net ×1

.net-3.5 ×1

c# ×1

extension-methods ×1

linq ×1

list ×1

performance ×1