Performance of LINQ Any vs FirstOrDefault != null

后端 未结 7 1777
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 12:05

There are multiple places in an Open Source Project (OSP) code I contribute, where it has to be determined if an element in a collection satisfies a certain condition.

7条回答
  •  情话喂你
    2020-11-28 12:19

    The problem with this question is that it is not asked within context. I am providing an answer because I see this a lot in code reviews and it bothers me. LINQ should not be an excuse to stop thinking.

    var people = new [] { "Steve", "Joe" };
    
    if (people.Any(s => s == "Joe"))
    {
        var joe = people.First(s => s == "Joe");
        // do something with joe
    }
    
    // if people is 1,000,000 people and joe is near the end do we want BigO to approach 2N here at worst case ?
    
    var joe1N = people.FirstOrDefault(s => s == "Joe");
    if (joe1N != null)
    {
        // do something with joe
    }
    
    // or do we want to ensure worst case is N by simply using a variable ?
    

提交回复
热议问题