12

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?

5
  • 2
    Start here: code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
    – Oded
    Feb 5, 2013 at 13:09
  • Then, go here: msmvps.com/blogs/jon_skeet/archive/tags/Edulinq/default.aspx
    – Oded
    Feb 5, 2013 at 13:10
  • 1
    LINQ is for querying object graphs. It is Language INtegrated Query - it allows you to query and manipulate collections.
    – Oded
    Feb 5, 2013 at 13:11
  • 1
    its probably a closable question as stands there may be a good question lurking in there on what problems linq is a good fit for though
    – jk.
    Feb 5, 2013 at 13:31
  • 1
    Linq is declarative. You state "what" you want without specifying "how" it's done. For linq that means you can use a queries to state what you want. Declarative code can be shorter and easier to understand for some problems.
    – mike30
    Feb 5, 2013 at 20:08

3 Answers 3

16

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.

7
  • I might have to delete this question now. The moderator commented that it is not fit for the community.. If you feel otherwise, please do tell me. Feb 5, 2013 at 13:27
  • 1
    I would add that if you rewrite it into LINQ and the original is still more readable, keep the original and remove the LINQ version. Sometimes, LINQ just doesn't add anything.
    – svick
    Feb 5, 2013 at 13:39
  • @svick in theory yes, I'm not sure I can think of any examples of this though ;)
    – jk.
    Feb 5, 2013 at 13:45
  • 1
    @jk. For example, ReSharper sometimes offers to convert my loop to LINQ using Aggregate(). I think most of the time, the loop is more readable.
    – svick
    Feb 5, 2013 at 13:47
  • @svick probably an issue of what you are used to, though I will admit that aggregate is a clumsy name for fold
    – jk.
    Feb 5, 2013 at 13:59
1

To answer the edited question: in short, it is beneficial to use LINQ whenever you have to implement "query" functionality (that's what the Q in LINQ stands for). Defining an exact domain is difficult, but it greatly simplifies a variety of tasks associated with extracting and manipulating data from collections.

To elaborate slightly, a lot of query functionality has been brought directly into the language (or rather, the various LINQ-implementors), so things like aggregations, ordering, grouping, filtering, projections, joins (and many more) are all handled for you. The LINQ-based solutions are also typically far shorter than if you were to implement them "by hand", and also communicate their intent far better.

A simple example which often helps convey the power of LINQ is to display the contents of a directory, grouped by extension. Run through a typical imperative implementation in your head - there will be lots of implementation details already at the outset. Perhaps we will use a Dictionary<String, List<String>> to index the files by extension. Of course, we'll have to check if a key already exists, instantiate a list, add to it, etc. It might go something like:

Dictionary<string, List<string>> fileGroups = new Dictionary<string, List<string>>();

foreach (string file in Directory.GetFiles(Environment.CurrentDirectory))
{
    string extension = Path.GetExtension(file).ToLower();

    if (!fileGroups.ContainsKey(extension))
    {
        fileGroups[extension] = new List<string>();
    }

    fileGroups[extension].Add(file);
}

Consider the LINQ equivalent:

var query = from file in Directory.GetFiles(Environment.CurrentDirectory)
            group file by Path.GetExtension(file).ToLower();

Notice that the query itself is only 2 lines, certainly shorter than any imperative solution we could have come up with. It is also pretty readable; the signal-to-noise ratio is higher than it was with the first solution. For those that are new to LINQ, you'd output the results of that query as follows:

foreach (var fileGroup in query)
{
    Console.WriteLine(String.Format("*** Files with extension: {0}", group.Key));

    foreach (string file in fileGroup)
    {
        Console.WriteLine(file);
    }
}

With more complex examples, the differences normally become even more vast (consider simply grouping by multiple fields, for example). So, to summarise, LINQ solves many "day to day" data querying problems in a way which is often shorter and more self-descriptive. This comes at a mild cost of having to learn the syntax and the technology, but the benefits greatly outweigh the negatives.

3
  • Do you classify map or fold as "queries" ? I don't really but I guess I could see it maybe.. I would normally think of an aggregate as a result of a computation, not a "query" Feb 6, 2013 at 15:04
  • @JimmyHoffa I'm mostly referring to the application of the computation to the underlying collection, not necessarily the computation itself. But there are probably gaping holes in my analogy, it's meant to be illustrative rather than 100% correct.
    – Daniel B
    Feb 6, 2013 at 15:38
  • @JimmyHoffa no, but then I'm not sure if there is a strict definition of what a query is to start with
    – jk.
    Feb 6, 2013 at 17:46
0

Different languages have been developed over time for the various types of data sources, for example SQL for relational databases and XQuery for XML. Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. for more visit http://msdn.microsoft.com/en-us/library/bb397906.aspx

1
  • Exactly LINQ is an abstraction API for working with collections. Some important benefits : using C# you get STATIC! Verification of your queries and transformations Mar 5, 2013 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.