Hi all. Linq noob here. I read about Linq but I don't quite understand in what circumstance to use Linq. Does anyone have an example?
thank
Jack
Hi all. Linq noob here. I read about Linq but I don't quite understand in what circumstance to use Linq. Does anyone have an example?
thank
Jack
anywhere you would have a loop over an array where LINQ offers the same functionality. For instance, say I want every unique name in an array of objects (string Name, int number, string description, etc)
var v = MyOjbectArray.Select(p => p.Name).Distinct();
Will give me an IEnumerable of unique names
LINQ is great when querying in memory collections and very useful as a data access method (LINQ to SQL or Entity Framework).
List<MyObject> list = new List<MyObject>();
// add items to the list
var result = list.Where(s => s.Name.StartsWith("A"));
Lots of samples / examples here: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
Kind of hard to summarise, giving the breadth of applications of LINQ. Essentially, I would say LINQ is a good alternative to looping/filtering/mapping arrays and lists (objects that implement IEnumerable in general). Combined with lambda expressions, it's sort of C#'s answer to functional programming (though still syntactically and ideologically quite different). Anyway, it can certainly make code much more succinct and readable in many cases.
The 101 LINQ Samples page on MSDN has many more samples than I could ever give (and covers just about every aspect of LINQ). Have a good read though, and ask here again if you're still unclear how you might use it for certain tasks.
I pretty much use it whenever I need to search a list. Its much easier than doing complicated foreach loops.
Here are 101 examples of possible situations when LINQ will come in handy.
There are just too many uses to describe.
Besides looking at the samples on http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx#, I suggest you download http://www.linqpad.net/, which comes with several examples you can run and play with to get used to it.
A very small list of some linq to [insert something here]:
linq to objects -> search, filter, join, and others on anything that implements IEnumerable<> (or any collection, given the .Cast<>)
linq2sql - work with db in a typed way
linq2xml - work with xml
linq to objects on js - http://www.codeplex.com/jsinq
LINQ to DataSet
linq to sharepoint - http://www.codeplex.com/LINQtoSharePoint
linq2json - http://james.newtonking.com/archive/2008/02/11/linq-to-json-beta.aspx
Bottom line, there are just too many uses. Some people have even used linq to express some puzzle solving scenarios.