C# – Where and When to use LINQ to Objects

.netc++linqvb.net

In which situations I should use LINQ to Objects?

Obviously I can do everything without LINQ. So in which operations LINQ actually helps me to code shorter and/or more readable?

This question triggered by this

Best Solution

I find LINQ to Objects useful all over the place. The problem it solves is pretty general:

  • You have a collection of some data items
  • You want another collection, formed from the original collection, but after some sort of transformation or filtering. This might be sorting, projection, applying a predicate, grouping, etc.

That's a situation I come across pretty often. There are an awful lot of areas of programming which basically involve transforming one collection (or stream of data) into another. In those cases the code using LINQ is almost always shorter and more readable. I'd like to point out that LINQ shouldn't be regarded as being synonymous with query expressions - if only a single operator is required, the normal "dot notation" (using extension methods) can often be shorter and more readable.

One of the reasons I particularly like LINQ to Objects is that it is so general - whereas LINQ to SQL is likely to only get involved in your data layer (or pretty much become the data layer), LINQ to Objects is applicable in every layer, and in all kinds of applications.

Just as an example, here's a line in my MiniBench benchmarking framework, converting a TestSuite (which is basically a named collection of tests) into a ResultSuite (a named collection of results):

return new ResultSuite(name, 
    tests.Select(test => test.Run(input, expectedOutput)));

Then again if a ResultSuite needs to be scaled against some particular "standard" result:

return new ResultSuite(name, 
    results.Select(x => x.ScaleToStandard(standard, mode)));

It wouldn't be hard to write this code without LINQ, but LINQ just makes it clearer and lets you concentrate on the real "logic" instead of the details of iterating through loops and adding results to lists etc.

Even when LINQ itself isn't applicable, some of the features which were largely included for the sake of LINQ (e.g. implicitly typed local variables, lambda expressions, extension methods) can be very useful.