Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Last active February 20, 2020 05:12
Show Gist options
  • Save joe-oli/06302bb9532f3dde2ce8d1227742f0d4 to your computer and use it in GitHub Desktop.
Save joe-oli/06302bb9532f3dde2ce8d1227742f0d4 to your computer and use it in GitHub Desktop.
LINQ and List methods
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.
----
Note how you can use:
myEnumerable.FirstOrDefault(predicate) vs myEnumerable.Where(predicate).FirstOrDefault()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment