Refactoring LINQ statements
In this final section of this chapter, we’ll review a few of the more common optimizations with LINQ code by focusing on some common improvements most codebases that use LINQ will benefit from.
Choosing the correct LINQ method
LINQ has several different ways of finding a specific item in a collection.
If you had an IEnumerable<Passenger>
interface named people
and wanted to find someone by their name, you might write code like this:
LinqExamples.cs
PassengerGenerator generator = new(); List<Passenger> people = generator.GeneratePassengers(50); Passenger me = people.FirstOrDefault(p => p.FullName == "Matt Eland"); Console.WriteLine($"Matt is in group {me.BoardingGroup}");
This code uses the LINQ FirstOrDefault
method, which searches the collection until it finds the first value that the arrow function evaluates as true. In this example, it’d find the first person with FullName
...