简体   繁体   中英

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

Newbie to C# here....

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.

What am I doing wrong? Why is result not coming back as a normal List object that I can manipluate in my code? Do I need to make another List object from it?

I am just trying to get the first Dictionary item out of the List and use it.

It depends on what you expected . Your code currently produces a 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.

This assumes the list has at least one entry though for which you would have to check.

This is a 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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM