Any and FirstOrDefault - best practice

suggest change

I won’t explain what Any and FirstOrDefault does because there are already two good example about them. See https://stackoverflow.com/documentation/c%23/68/linq-queries/5098/any#t=201707200324548979636 and https://stackoverflow.com/documentation/c%23/68/linq-queries/329/first-firstordefault-last-lastordefault-single-and-singleordefault#t=201707200328069088515 for more information.

A pattern I often see in code which should be avoided is

if (myEnumerable.Any(t=>t.Foo == "Bob"))
{
    var myFoo = myEnumerable.First(t=>t.Foo == "Bob");
    //Do stuff
}

It could be written more efficiently like this

var myFoo = myEnumerable.FirstOrDefault(t=>t.Foo == "Bob");
if (myFoo != null)
{
    //Do stuff
}

By using the second example, the collection is searched only once and give the same result as the first one. The same idea can be applied to Single.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


LINQ Queries:
* Except
* Any
* JOINS
* Zip
* All
* Basics
* Where
* Sum
* Any and FirstOrDefault - best practice
* Concat
* Union

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
64 LINQ Queries
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script