Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
2  
Start here: code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b –  Oded Feb 5 '13 at 13:09
1  
LINQ is for querying object graphs. It is Language INtegrated Query - it allows you to query and manipulate collections. –  Oded Feb 5 '13 at 13:11
4  
I would also add that this kind of question is not considered constructive on Programmers, as it is a request for resources. Do you mind deleting it when you can? –  Oded Feb 5 '13 at 13:14
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 '13 at 13:31
3  
Don't delete the question now please, I've editted it and if the community doesn't want it with the edit, they can close it again (then delete it). –  Jimmy Hoffa Feb 6 '13 at 15:07
show 7 more comments

3 Answers

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.

share|improve this answer
1  
I'd +1 this, if I had enough reputation –  user1816120 Feb 5 '13 at 13:19
    
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. –  user1816120 Feb 5 '13 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 '13 at 13:39
    
@svick in theory yes, I'm not sure I can think of any examples of this though ;) –  jk. Feb 5 '13 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 '13 at 13:47
show 3 more comments

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.

share|improve this answer
    
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" –  Jimmy Hoffa Feb 6 '13 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 '13 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 '13 at 17:46
add comment

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

share|improve this answer
    
Exactly LINQ is an abstraction API for working with collections. Some important benefits : using C# you get STATIC! Verification of your queries and transformations –  AndreasScheinert Mar 5 '13 at 9:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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