Tuesday, July 28, 2009

C#3 anonymous types, parameters and LINQ for XML

Crash learning to work with LINQ XML (see sample code below to get a distinct list from an XML file written by a reporting services report) re-introduced me to a really usefull feature of C#3 called anonymous types where you can create an object on the fly. You can then use that object in the same method, however if you wish to pass it to another method then things start getting complicated. This blog note Anthony Steele's Blog : C#3 anonymous types as parameters points you in the right direction to whats possible.

(He also mentions a very good book on C#3 (by Bill Wagner) to hone your skills)


Note: as a learning LINQ is a lot of trial and error you can test your LINQ code in a very helpful utility called:http://www.linqpad.net/

Sample LINQ code
XDocument xDoc = XDocument.Load(@"c:\temp\RSD.xml");
var q = (from e1 in xDoc.Descendants("{SchemaName}Detail").Distinct()
let div = e1.Attribute("Division").Value
let cc = e1.Attribute("CostCode").Value
select new { div, cc }).Distinct();

q.Dump(); //this shows you the contents of q

No comments: