[英]How do I get a usabled List object for this code in C# using LINQ to XML?
Newbie to C# here.... C#的新手在这里。
I have the following code: 我有以下代码:
var xdoc = XDocument.Parse(xml);
var result = xdoc.Root.Elements("item")
.Select(itemElem => itemElem.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value))
.ToList();
but when I try to use result
as I would any List
object, such as result.Item
, it doesn't work. 但是,当我尝试像使用任何
List
对象一样使用result
,例如result.Item
,它将不起作用。
What am I doing wrong? 我究竟做错了什么? Why is result not coming back as a normal List object that I can manipluate in my code?
为什么结果不返回为我可以在代码中使用的普通List对象? Do I need to make another List object from it?
我是否需要从中制作另一个List对象?
I am just trying to get the first Dictionary item out of the List and use it. 我只是想从列表中取出第一个Dictionary项并使用它。
It depends on what you expected . 这取决于您的期望 。 Your code currently produces a
List<Dictionary<string,string>>
. 您的代码当前产生一个
List<Dictionary<string,string>>
。 So each entry in the list would be a dictionary. 因此,列表中的每个条目都是一本字典。
You can access each dictionary as you usually would access list elements, ie 您可以像平常访问列表元素一样访问每个字典,即
string firstResult = result[0]["key"];
The first part [0]
is the indexer of the list the second part ["key"]
is the indexer of the dictionary - this would return the value for the key "key"
of the first dictionary in your list. 第一部分
[0]
是列表的索引器,第二部分["key"]
是字典的索引器-这将返回列表中第一个字典的键"key"
的值。
This assumes the list has at least one entry though for which you would have to check. 假设列表中至少有一个条目需要您检查。
This is a List<Dictionary<String, String>>
. 这是一个
List<Dictionary<String, String>>
。 Each element in the list is a Dictionary. 列表中的每个元素都是一个字典。
It would help to know what you wanted to do with it. 这将有助于您知道要使用它做什么。
But some examples are: 但是一些示例是:
//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.