TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Tuesday, November 27, 2007 #

I'm sure you've heard by now the Visual Studio 2008 is RTM. If you haven't already, play around a bit with object/collection initializers and LINQ. One interesting thing  I've learned today is the “let” clause which allows you to define a subexpression in a LINQ query. Also you can generate XML fairly easily in your LINQ queries (or anything else you want to transform for that matter).

class Program

{

    static void Main(string[] args)

    {

        List<Person> people = new List<Person>(){

            new Person { Name = "Jack", Age = 22, FavoriteColors = new string[] { "Green", "Red" } },

            new Person { Name = "Jill", Age = 33, FavoriteColors = new string[] { "Black", "Blue" } }

        };

 

        var xmlSource = new XElement("People",

        from person in people

        let colors = String.Format("{0},{1}", person.FavoriteColors[0], person.FavoriteColors[1])

        select new XElement("Person",

                   new XElement("Name", person.Name),

                   new XElement("Age", person.Age),

                   new XElement("FavoriteColors", colors)

                )

            );

 

        Console.WriteLine(xmlSource);

 

        /* output:

            <People>

              <Person>

                <Name>Jack</Name>

                <Age>22</Age>

                <FavoriteColors>Green,Red</FavoriteColors>

              </Person>

              <Person>

                <Name>Jill</Name>

                <Age>33</Age>

                <FavoriteColors>Black,Blue</FavoriteColors>

              </Person>

            </People>

         */

    }

}

posted @ 2:48 PM | Feedback (0)