Tag Archives: LINQ 2010 C#

Creating XML Using the XmlDocument Class

Most developers have used the XmlDocument class when creating new XML content, and it works fine. The problem is that its use is somewhat opaque. That is, the code isn’t readable (it’s difficult to discern what the resulting XML will look like as you read it), and it’s not always obvious how to create the XML content that you need.
Imagine that you need to create just this simple bit of XML content:

You might think creating this content would be simple, if you hadn’t worked with the XmlDocument class, but it actually requires a bit of code. The XmlDocument object requires you to take several steps each time you need to add a new node to the root document. Given a reference to the XML document, you must:

  • Call a method of the root node (CreateProcessingInstruction, CreateElement, CreateComment, and so on), creating the new node. You must pass necessary values to the constructor of the new node to initialize the node.
  • Append the new node as a child of an existing node, by calling the AppendChild method of the node.

The sample procedure, CreateXmlDocument, demonstrates creating the XML shown previously, using the pre-LINQ XmlDocument class:

 

The code starts by creating a new XmlDocument object, the root of the XML content:

 

As mentioned earlier, for each node you create, you must take two steps, creating the node and then appending it as a child of its new parent. The sample procedure starts by creating and appending the XML declaration:

 

Then, it creates and appends the comment node:

 

Finally, the code creates the document element, named Customers, and appends it as a child of the document:

 

To show how to create an XML file, the code calls the Save method of the XmlDocument object, and then displays the contents of the file:

 

NOTE The sample application contains several different overloaded versions of the DisplayResults method, and a few overloads for the DisplayFormattedResults methods. The sample procedures call these “helper” methods, and each displays output in the Console window. The DisplayFormattedResults method calls the
String.Format method for you, given a template in the first parameter. If you’re interested, you can investigate these methods.

ldn-expertkgetzThis post is an excerpt from the online courseware for our Microsoft LINQ Using Visual C# 2010 course written by expert Ken Getz.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Generic Lists in LINQ

LINQ allows you to query over any type of generic list. The most common list type you’ll use is List, but LINQ allows you to work with any of the following list types, in the System.Collections.Generic namespace unless otherwise specified:

  • List<T>
  • LinkedList<T>
  • Queue<T>
  • Stack<T>
  • HashSet<T>
  • System.Collections.ObjectModel.Collection<T>
  • System.ComponentModel.BindingList<T>

Just to prove the point, the sample project includes the QueryGenericList method. This method performs similar work to the earlier QueryArray method, this time showing both query syntax, and functional syntax. Listing 2 shows the entire procedure.


Listing 2. The QueryGenericList method shows off several different techniques, including query vs. functional syntax.

Running this procedure displays the output shown in the Figure below.

The Figure above. The QueryGenericList procedure provides a list of files.

The QueryGenericList procedure starts by retrieving the array of files, and copying the data into a generic list:

Next, the code uses standard query syntax to retrieve from the list all the files whose length is less than 1000 bytes, ordered first by length in descending order, and then for files with matching lengths, by file name. The query retrieves an anonymous type containing the Name and Length properties of the file:

Finally, the procedure demonstrates the equivalent query, created using function syntax instead. This query returns the same data in the same order, but does it by calling extension methods with lambda expressions defining their behavior:

Note a few things about this query definition:

  • The Where function accepts a lambda expression that returns true or false for each item in the collection. Items for which the lambda expression returns false are excluded from the collection:
  • The OrderByDescending method (and its “cousin,” the OrderBy method) accepts a lambda expression that returns information indicating how to sort the data. In this case, the sorting occurs based on the Length property of each FileInfo object:
  • Using the standard query syntax, you can indicate ordering by multiple columns by simply including the columns separated with a comma. In function syntax, you must use the ThenBy or ThenByDescending method to indicate a secondary sort. As a parameter to the method, pass a lambda expression which, again, indicates the sort order. In this case, the secondary sort uses the Name property of the input FileInfo object:
  • The Select method accepts a lambda expression that identifies which field or fields you want the query to return. In this case, the query returns an anonymous type containing the Name and Length properties 

NOTE Remember, all the techniques you’ve seen in this example apply to any type of LINQ query, not just LINQ to Objects, and not just queries that work with generic lists.

TIP: The System.Linq.Enumerable class provides a large number of extension methods that add behavior to queryable objects, much like the Select, Where, OrderBy, ThenBy, OfType, and other methods you’ve already seen. Later sections in this chapter introduce many of these methods. For more information, review the Microsoft documentation for the System.Linq.Enumerable class and its many methods.

 

ldn-expertkgetzThis post is an excerpt from the online courseware for our Microsoft LINQ Using Visual C# 2010 course written by expert Ken Getz.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.