C# – What problem domain is LINQ made for

clinqprofessional-development

Each time I see a question posted on Stack Overflow on C#, I see at least one or two answers posted that solve a problem with LINQ. Usually people with very high reputation seem to use LINQ like pros.

So my question is, what problem domain is LINQ supposed to be used for?

Also on side notes: Are there any purposes in which it should be avoided? Does the size of dataset affect the performance of LINQ queries?

Best Answer

LINQ is primarily designed to allow pure functional queries and transformations on sequences of data (you will notice that all the LINQ extensions take Func delegates but not Action delegates). Consequently the most common case of a loop that does not fit with LINQ very well is one that is all about non-pure functional side effects, e.g.

foreach(var x in list) Console.WriteLine(x);

To get better at using LINQ, just practice using it.

Every time you are about to write a for or foreach loop to do something with a collection, stop, consider if it's a good fit for LINQ (i.e. it's not just performing an action/side effect on the elements), and if so force yourself to write it using LINQ.

You could also write the foreach version first then rewrite to a LINQ version.

As svick points out, LINQ should be about making your program more readable. It is usually good at this as it tends to emphasize the intent of the code rather than the mechanism; however if you find you cannot make your queries more readable than a simple loop, feel free to stick with the loop.

If you need exercises to practice, most functional programming exercises will map nicely to LINQ e.g. 99 problems (especially the first 20 or so) or project euler.