Linq and XML
Written by Mike James   
Tuesday, 28 October 2014
Article Index
Linq and XML
Select And Project

Select and the Projection

The Select part of a Linq expression normally works as a projection operator that “reduces” the size of the data structure returned by a query.

For example, it can be use to select which “columns” are returned from a SQL query which otherwise would return a complete record.

For example, the query

var q = from E in root.Elements()
  where E.Name == "Name"
   select E;

returns a deep copy in the sense that the XElement corresponding to Name brings with it an entire subtree.

Suppose you want a “shallow” copy, i.e. just the node and its text value. In this case we can project the XElement to a string that contains all of the XText in the subtree:

var q = from E in root.Elements()
 where E.Name == "Name"
  select E.Value;

However, projection can also be used to create a larger or completely different type using the data returned by the query.

For example, you could perform a Linq to SQL query to return some values and then package them up into an XML tree.

To understand how this works all you really have to do is focus on the role of the “range” variable. It is set to each of the objects that match the selection criterion and eventually this can be used to construct any other data type.

For example, suppose you wanted to reconfigure the XML tree that stored the first and second names in our example into a different XML tree. You could do the job using a slightly more advanced select projection:

var q = from E in root.Elements()
 where E.Name == "Name"
  select new XElement("NameRecord",
    new XElement("Name1",
              E.Element("First").Value),
    new XElement("Name2",
              E.Element("Second").Value)
);

In this case we take each of the selected elements and build a new XML tree using their values and it is a collection of these new XML trees that are returned.

While this isn’t a particularly useful transformation it gives you the basic idea, i.e. use the result of the query to build new types, and you can generalise it to other situations. In more complex transformations it can even be useful to work out intermediate results to be used later within the select clause.

To create a variable within a Linq expression you simply use the let keyword. For example the previous query can be re-written:

var q = from E in root.Elements()
 where E.Name == "Name"
  let z1=E.Element("First")
  let z2=E.Element("Second")
 select
  new XElement("NameRecord",
  new XElement("Name1",z1.Value),
  new XElement("Name2",z2.Value));

In this case the let keywords create two new variables z1 and z2 which are used to hold the child elements that match the two sub-queries. Notice that the result is exactly the same if you don’t use the temporary variables.

Notice that you can even use the select to modify the existing XML tree using SetValue and so on but – be warned a tree is a complicated structure and you need to be sure that what you are trying to do can be done in every case.

In most cases it is much better to use the functional approach to build a new tree as part of the select clause. Notice that this is made even more powerful by the simple fact that the constructors can accept IEnumeration sequences and will automatically iterate through all of the objects thus adding them to the new tree.

For example, consider:

var q = from E in root.Elements()
 where E.Name == "Name"
  select
   new XElement("NameRecord",
                  root.Attributes(),
   new XElement("Name1",
   E.Element("First").Value),
   new XElement("Name2",
            E.Element("Second").Value));

Notice that the use of root.Attributes adds all of the attributes in the collection to the new XElement corresponding to the tag <NameRecord>.

Linq, and Linq to XML in particular, provides so many ways of doing things that it can leave you feeling slightly queasy about the whole thing and it is certain that you can write code that is deep and impenetrable – don’t.

csharp

Related Articles

The LINQ principle

XML in C# - Using XElement

Programmer's Introduction to XML

       

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

 

Banner


XML in C# - Using XElement

.NET has some really easy-to-use facilities for creating and editing XML. Many of these facilities were introduced to make Linq to XML work better, but you can make use of them in more general situati [ ... ]



What's The Matter With Pointers?

Back in the days when C was the language of choice, pointers meant programming and vice versa. Now in the more sophisticated and abstract days of C#, and even C++, raw pointers are a facility that is  [ ... ]


Other Articles

 

blog comments powered by Disqus

<ASIN:0735640572>

<ASIN:0321637003>

<ASIN:0321658701>

<ASIN:0596004206>

<ASIN:1118162137>

<ASIN:0321877586>



Last Updated ( Tuesday, 28 October 2014 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.