如何在c#中使用LINQ to XML获得此代码的可用列表对象?
本文关键字:代码 对象 列表 XML to LINQ | 更新日期: 2023-09-27 18:17:41
这里是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();
但是当我尝试使用result
作为任何List
对象时,例如result.Item
,它不起作用。
我做错了什么?为什么结果不回来作为一个正常的列表对象,我可以在我的代码操纵?我需要从它做另一个列表对象吗?
我只是想从列表中获得第一个字典项并使用它。
这取决于你期望的。您的代码当前产生一个List<Dictionary<string,string>>
。因此,列表中的每个条目都是一个字典。
您可以像访问列表元素一样访问每个字典,即
string firstResult = result[0]["key"];
第一部分[0]
是列表的索引器,第二部分["key"]
是字典的索引器-这将返回列表中第一个字典的键"key"
的值。
这里假设列表中至少有一个条目需要检查。
这是List<Dictionary<String, String>>
。列表中的每个元素都是一个Dictionary。
知道你想用它做什么会有帮助。
但是一些例子是:
//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"])