Prev | Current Page 621 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Of course, the typed dataset can write
XML directly, but let??™s convert our original in-memory version for simplicity. To start
with, we??™ll just generate a list of the users. Listing 12.14 creates a list of user elements
within a users element, and then writes it out; the output is shown beneath the listing.
var users = new XElement("users",
from user in SampleData.AllUsers
select new XElement("user",
new XAttribute("name", user.Name),
new XAttribute("type", user.UserType))
);
Console.WriteLine (users);
// Output








I hope you??™ll agree that listing 12.14 is simple, once you??™ve got your head around the
idea that the contents of the top-level element depend on the result of the embedded
query expression. It??™s possible to make it even simpler, however. I??™ve written a small
extension method on object that generates an IEnumerable based on
the properties of the object it??™s called on, which are discovered with reflection. This is
ideal for anonymous types??”listing 12.15 creates the same output, but without the
explicit XAttribute constructor calls.


Pages:
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633