Last Updated: 6/26/2012
Last Updated: 6/26/2012
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);
// The non-SelectMany way string[] parts = new string[] {"This is my", "test string", "you see"}; var w = parts.Select(o => o.Split(' ')); foreach (var i in w) Console.WriteLine(i.Count()); // displays 3, 2, 2 foreach (var i in w) foreach(var j in i) Console.WriteLine(j); // displays 7 words // The SelectMany way // string.Split(..) returns IEnumerable<string>, so the final result is // an IEnumerable<string> which is all the other IEnumerable<string> // concatinated together. // (Note that this isn't recursive. If we returned IEnumerable<IEnumerable<int>>s // then the result would be IEnumerable<IEnumerable<int>> not IEnumerable<int>) var many = parts.SelectMany(o => o.Split(' ')); foreach (var i in many) Console.WriteLine(i); // displays 7 words
Last Updated: 6/26/2012
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
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);
var interesting = lps.Where((item, index) => { Console.WriteLine(index); return true; }).ToArray();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...).
from o in outer from i in inner select new {o, i};
var results = from l in left join r in right on l.id = r.id into j from z in j.DefaultIfEmpty() select new {l.id, x = (z == null ? "No RHS record" : z.someValue)} foreach(var r in result) Console.WriteLine("{0}, {1}", r.id, r.x);