I\'m looking at some code that takes an IEnumerable
var myEnumerable = .
Or you can do the following way:
var match = myEnumerable.Where(value => value.Aaa == aaa && value.Bbb == bbb)
.FirstOrDefault();
The LINQ equivelent would be to use FirstOrDefault:
var match = myEnumerable.FirstOrDefault(value => value.Aaa == aaa && value.Bbb == bbb);
Just for reference, here is a table of some old .NET 2 style List<>
instance methods, and their equivalent extension methods in Linq:
METHOD IN List<> METHOD IN Linq
------------------------------------------------------------------------------------------
list.Contains(item) query.Contains(item)
list.Exists(x => x.IsInteresting()) query.Any(x => x.IsInteresting())
list.TrueForAll(x => x.IsInteresting()) query.All(x => x.IsInteresting())
list.Find(x => x.IsInteresting()) query.FirstOrDefault(x => x.IsInteresting())
list.FindLast(x => x.IsInteresting()) query.LastOrDefault(x => x.IsInteresting())
list.FindAll(x => x.IsInteresting()) query.Where(x => x.IsInteresting())
list.ConvertAll(x => x.ProjectToSomething()) query.Select(x => x.ProjectToSomething())
Of course some of them are not entirely equivalent. In particular Linq's Where
and Select
use deferred execution, while FindAll
and ConvertAll
of List<>
will execute immediately and return a reference to a new List<>
instance.
FindLast
will often be faster than LastOrDefault
because FindLast
actually searches starting from the end of the List<>
. On the other hand LastOrDefault(predicate)
always runs through the entire sequence (starting from the first item), and only then returns the most "recent" match.