简体   繁体   中英

Parse a Dictionary<string, List<KeyValuePair<string, string>>> object using LINQ

I have this dictionary object

Dictionary<string, List<KeyValuePair<string, string>>>  

Using LINQ method syntax, how to iterate over this object and extract the values if Key="doctype"?

How can I achieved the same result using LINQ?

foreach (var type in docuObject.DocuObject)
{
    foreach (var t in type.Value)
    {
        if (t.Key.ToString() == "doctype")
        {
            Console.WriteLine(t.Value.ToString());
        }
    }
}

Any help is appreciated.

Dictionary object

Easy :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication100
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string STATUS_XML_FILENAME = @"c:\temp\test2.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string,Dictionary<string,string>> dict = doc.Descendants("properties")
                .GroupBy(x => (string)x.Attribute("value"), y => y.Elements("property")
                    .GroupBy(a => (string)a.Attribute("name"), b => (string)b.Attribute("value"))
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}
var result = 
  from type in docuObject.DocuObject
  from t in type.Value
  where t.Key == "doctype"
  select t.Value

You can then foreach over the result if you want to write them all to the console.

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