簡體   English   中英

如何使用LINQ to XML在C#中獲得此代碼的可用列表對象?

[英]How do I get a usabled List object for this code in C# using LINQ to XML?

C#的新手在這里。

我有以下代碼:

var xdoc = XDocument.Parse(xml);
            var result = xdoc.Root.Elements("item")
                .Select(itemElem => itemElem.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value))
                .ToList();

但是,當我嘗試像使用任何List對象一樣使用result ,例如result.Item ,它將不起作用。

我究竟做錯了什么? 為什么結果不返回為我可以在代碼中使用的普通List對象? 我是否需要從中制作另一個List對象?

我只是想從列表中取出第一個Dictionary項並使用它。

這取決於您的期望 您的代碼當前產生一個List<Dictionary<string,string>> 因此,列表中的每個條目都是一本字典。

您可以像平常訪問列表元素一樣訪問每個字典,即

string firstResult = result[0]["key"];

第一部分[0]是列表的索引器,第二部分["key"]是字典的索引器-這將返回列表中第一個字典的鍵"key"的值。

假設列表中至少有一個條目需要您檢查。

這是一個List<Dictionary<String, String>> 列表中的每個元素都是一個字典。

這將有助於您知道要使用它做什么。

但是一些示例是:

//Get the First Dictionary Item, then Iterate through all the items in the first dictionary.
var firstItem = results.First();
foreach(var kvPair in firstItem)
{
    var key = kvPair.Key;
    var val = kvPair.Value;
}

//Loop through each Dictionary getting values from each.
foreach (var result in results)
{
    var wordValue = result["word"];
    var defValue = result["def"];
}

//Create a list of all the values for the Elements with the key "word".
var valuesForAllWords = 
  results
  .Select(r => r["word"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM