使用LINQ解析Dictionary <string,list <keyvaluepair <string,=“” string =“” >>>对象

时间:2019-02-21 14:09:23

标签: c# xml linq

我有这个字典对象

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

使用LINQ方法语法,如果Key =“ doctype”,如何遍历此对象并提取值?

如何使用LINQ达到相同的结果?

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

感谢您的帮助。

Dictionary object

2 个答案:

答案 0 :(得分:0)

简单:

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());
        }
    }
}

答案 1 :(得分:0)

var result = 
  from type in docuObject.DocuObject
  from t in type.Value
  where t.Key == "doctype"
  select t.Value

如果您要将它们全部写入控制台,则可以在foreachresult