I've found LINQ to be handy in literally any scenario where I'm working with collections of objects. The main things you do with collections of objects are:
- Search them for items matching some characteristic
- Traverse them to calculate some aggregate value
- Visit each item in the collection and calculate some value based on it (translation)
- Rearranging its contents for some purpose (transformation)
Each of these scenarios has a number of LINQ methods that are designed to help with the task:
- For searching, there's
Where()
, First()
, Any()
, All()
, Last()
- For aggregation, there's
Aggregate()
, Average()
Sum()
, Max()
, Min()
- For translation there's
Select()
and SelectMany()
- For transformation there's
OrderBy()
, GroupBy()
, Reverse()
And a few other odds and ends that I'm not sure how to categorize in the above for - for example the set operations Union()
and Intersect()
.
In general, all of these functions do the work of hand-coded loops, but have the advantage of improving legibility because they help to replace several lines worth of code with a few LINQ operations that are named after what they do. For example, consider
string[] input;
var output = new string[input.Length];
for(int i = 0; i < input.Length; i++)
{
output[input.Length - i - 1] = input[i];
}
versus:
var output = input.Reverse().ToArray();
Another advantage is that it's easy to string them together to get more complex behavior. Say that instead you wanted to get only the unique values in the array, and sort them. Right now I'm feeling too lazy to hand-code a solution to it, but I'm sure whatever it is it would be much longer and harder to read than
var output = input.Distinct().OrderBy(x=>x).ToArray();
And it definitely would take longer, which is why I don't feel like writing it.