Any and FirstOrDefault - best practice

suggest change

I won’t explain what Any and FirstOrDefault do because there are already two good examples. 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
}

The second example searches the collection only once and gives the same result as the first. The null check assumes a reference type; a value type’s default is not null. The same idea can be applied to Single and SingleOrDefault.

Feedback about page:

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



Table Of Contents