Any and First(OrDefault) - best practice C# with Example
I won't explain what Any and FirstOrDefault does because there are already two good example about them. See
Any and First, FirstOrDefault, Last, LastOrDefault, Single, and SingleOrDefault 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");
It could be written more eﬃciently like this
var myFoo = myEnumerable.FirstOrDefault(t=>t.Foo == "Bob");
if (myFoo != null)
By using the second example, the collection is searched only once and give the same result as the ﬁrst one. The
same idea can be applied to Single.