Compartir a través de


How to: Project a New Type (LINQ to XML)

Other examples in this section have shown queries that return results as IEnumerable<T> of XElement, IEnumerable<T> of string, and IEnumerable<T> of int. These are common result types, but they are not appropriate for every scenario. In many cases you will want your queries to return an IEnumerable<T> of some other type.

Example

This example shows how to instantiate objects in the select clause. The code first defines a new class with a constructor, and then modifies the select statement so that the expression is a new instance of the new class.

This example uses the following XML document: Sample XML File: Typical Purchase Order (LINQ to XML).

class NameQty {
    public string name;
    public int qty;
    public NameQty(string n, int q)
    {
        name = n;
        qty = q;
    }
};

class Program {
    public static void Main() {
        XElement po = XElement.Load("PurchaseOrder.xml");

        IEnumerable<NameQty> nqList =
            from n in po.Descendants("Item")
            select new NameQty(
                    (string)n.Element("ProductName"),
                    (int)n.Element("Quantity")
                );

        foreach (NameQty n in nqList)
            Console.WriteLine(n.name + ":" + n.qty);
    }
}
Public Class NameQty
    Public name As String
    Public qty As Integer
    Public Sub New(ByVal n As String, ByVal q As Integer)
        name = n
        qty = q
    End Sub
End Class

Public Class Program
    Shared Sub Main()
        Dim po As XElement = XElement.Load("PurchaseOrder.xml")

        Dim nqList As IEnumerable(Of NameQty) = _
            From n In po...<Item> _
            Select New NameQty( _
                n.<ProductName>.Value, CInt(n.<Quantity>.Value))

        For Each n As NameQty In nqList
            Console.WriteLine(n.name & ":" & n.qty)
        Next
    End Sub
End Class

This example uses the M:System.Xml.Linq.XElement.Element method that was introduced in the topic How to: Retrieve a Single Child Element (LINQ to XML). It also uses casts to retrieve the values of the elements that are returned by the M:System.Xml.Linq.XElement.Element method.

This example produces the following output:

Lawnmower:1
Baby Monitor:2

See Also

Concepts

Projections and Transformations (LINQ to XML)