Last Updated: 6/26/2012



Last Updated: 6/26/2012

Conversion Operators

Joining Operators

Ordering Operators


It is possible to group by anonymous types (e.g. group p by new {p.Surname, p.ForeName}) which the Key will then expose. For example:

            var results = from p in people select p group by new {p.ZipCode, p.AgeInYears};
            foreach(var r in results) Console.WriteLine("{0},{1},{2}", r.Key.ZipCode, r.Key.AgeInYears, r.Count());

Anonymous types should be used over strong types for multi-field grouping unless the strong type has implemented GetHashcode and Equals to look at property equavalence rather than object reference equivalence.

The 'into' keyword allows groups to be used later in the query (e.g. subtotals)

            var result=from o in orders
                group o by orders.customerNumber into g
                select new {customerNumber=g.Key, amount=g.Sum(o => o.amount)}
            foreach(var r in result) Console.WriteLine(r.customerNumber, r.amount);

Set Operators

Projection Operators


Last Updated: 6/26/2012

Generating XML from LINQ

var content = from p in people 
    select new XElement("person",
            new XElement("name", p.Name),
            new XElement("address", 
                new XElement("line1", p.AddressLine1),
                new XElement("zip", p.AddressZipCode)
XDocument doc = new XDocument(new Element("people", content));


Last Updated: 6/26/2012

let keyword

Assigns a value that can be used later on in the query.
            int[] data = {1,2,3,4};
            var variance = from datum in data 
                              let average = data.Average()
                              select math.Abs(datum - average); 
The let keyword is compiler sugar. Under the covers, the compiler is actually cascading anonymous types:
            int[] data = {1,2,3,4};
            var variance = data.Select(datum => new {datum=datum, average=data.Average()})
                               .Select(temp => select math.Abs(temp.datum - temp.average); 


Where, Select and SelectMany supports a second arg: the index of the item in the source collection
        var interesting = lps.Where((item, index) =>
                return true;
This is only supported in the extension method queries lanuage (i.e. y.Where((x,b) => ...). There is no way to express it in the query form (from x in y where x...).



Cartesian Joins

            from o in outer
            from i in inner
            select new {o, i};

(Left) Outer Join

This appears to be rather messy. ?? TODO: Validate this. Not sure I got it right ??
            var results = from l in left
                            join r in right on = into j
                            from z in j.DefaultIfEmpty()
                            select new {, x = (z == null ? "No RHS record" : z.someValue)}
            foreach(var r in result) Console.WriteLine("{0}, {1}",, r.x);