Export (0) Print
Expand All

How to: Sort Elements

This example shows how to write a query that sorts its results.

Example

This example uses the following XML document: Sample XML File: Numerical Data (LINQ to XML).

XElement root = XElement.Load("Data.xml");
IEnumerable<decimal> prices =
    from el in root.Elements("Data")
    let price = (decimal)el.Element("Price")
    orderby price
    select price;
foreach (decimal el in prices)
    Console.WriteLine(el);

This code produces the following output:

0.99
4.95
6.99
24.50
29.00
66.00
89.99

The following example shows the same query for XML that is in a namespace. For more information, see Working with XML Namespaces.

This example uses the following XML document: Sample XML File: Numerical Data in a Namespace.

XElement root = XElement.Load("DataInNamespace.xml");
XNamespace aw = "http://www.adatum.com";
IEnumerable<decimal> prices =
    from el in root.Elements(aw + "Data")
    let price = (decimal)el.Element(aw + "Price")
    orderby price
    select price;
foreach (decimal el in prices)
    Console.WriteLine(el);

This code produces the following output:

0.99
4.95
6.99
24.50
29.00
66.00
89.99

See Also

Concepts

Basic Queries (LINQ to XML)

Other Resources

Sorting Data




Build Date:

2012-08-02
Show:
© 2014 Microsoft