13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

LINQ to XML341You can nest query expressions and do all k<strong>in</strong>ds of other clever th<strong>in</strong>gs with them.List<strong>in</strong>g 12.16 generates an element conta<strong>in</strong><strong>in</strong>g the project <strong>in</strong>formation: the notificationsubscriptions for a project are embedded with<strong>in</strong> the project element by us<strong>in</strong>g anested query. The results are shown beneath the list<strong>in</strong>g.List<strong>in</strong>g 12.16Generat<strong>in</strong>g projects with nested subscription elementsvar projects = new XElement("projects",from project <strong>in</strong> SampleData.AllProjectsselect new XElement("project",new XAttribute("name", project.Name),new XAttribute("id", project.ProjectID),from subscription <strong>in</strong> SampleData.AllSubscriptionswhere subscription.Project == projectselect new XElement("subscription",new XAttribute("email", subscription.EmailAddress))));Console.WriteL<strong>in</strong>e (projects);// OutputThe two queries are highlighted <strong>in</strong> bold. There are alternative ways of generat<strong>in</strong>g thesame output, of course—you could use a s<strong>in</strong>gle query that groups the subscriptions byproject, for <strong>in</strong>stance. The code <strong>in</strong> list<strong>in</strong>g 12.16 was just the first way I thought of tackl<strong>in</strong>gthe problem—and <strong>in</strong> cases where the performance isn’t terribly important itdoesn’t matter that we’ll be runn<strong>in</strong>g the nested query multiple times. In productioncode you’d want to consider possible performance issues more carefully, of course!I won’t show you all the code to generate all the elements—even with LINQ toXML, it’s quite tedious just because there are so many attributes to set. I’ve placed it all<strong>in</strong> a s<strong>in</strong>gle XmlSampleData.GetElement() method that returns a root XElement. We’lluse this method as the start<strong>in</strong>g po<strong>in</strong>t for the examples <strong>in</strong> our f<strong>in</strong>al avenue of<strong>in</strong>vestigation: query<strong>in</strong>g.12.4.3 Queries <strong>in</strong> LINQ to XMLYou may well be expect<strong>in</strong>g me to reveal that XElement implements IEnumerable andthat LINQ queries come for free. Well, it’s not quite that simple, because there are soLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!