Saturday, June 11, 2016

The .Find Lambda is going to throw an exception when it can't find a match.

That is its Achilles heel. It's otherwise more efficient than using .Where or, my old crutch, the foreach loop to fish something out of a collection. You'll have to wrap your .Find implementation in a try/catch if there is a possibility of a fail. Don't expect to map the result from a .Find to a string and have the string just be null when the .Find finds nothing. That's not how things work in C#.

 
 

Addendum 6/13/2016: This isn't true at all as it turns out. .Find, like .FirstOrDefault will return the default for a type if it can't make a match, for example a null value for a string. This suggests that .Find has existed since C# 2.0 at lists while .FirstOrDefault came later with the LINQ and Lambda stuff and is for IEnumerable more universally.

No comments:

Post a Comment