共用方式為


HOW TO:規劃新型別 (LINQ to XML)

本節中的其他範例顯示的查詢會傳回結果,當做 string 之 XElement, IEnumerable<T>IEnumerable<T>,以及 int 的 IEnumerable<T>。 這些是常見的結果型別,但這些型別不適用於每個案例。 在許多情況下,您會希望您的查詢傳回其他型別的 IEnumerable<T>

範例

此範例顯示如何具現化 select 子句中的物件。 此程式碼會先利用建構函式定義新的類別,然後修改 select 陳述式,讓運算式成為新類別的新執行個體。

此範例使用下列 XML 文件:範例 XML 檔案:典型的採購訂單 (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

此範例會使用主題 HOW TO:擷取單一子項目 (LINQ to XML)中所引入的 M:System.Xml.Linq.XElement.Element 方法。 它也會使用轉換以擷取 M:System.Xml.Linq.XElement.Element 方法所傳回的元素值。

此範例會產生下列輸出:

Lawnmower:1
Baby Monitor:2

請參閱

概念

規劃和轉換 (LINQ to XML)