![](/img/trans.png)
[英]In C# Using System.Xml.Linq XText how do I get an & in the document instead of &
[英]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.