LINQ在C#字典中选择

use*_*829 24 c# linq dictionary

我在C#中有下一本字典

Dictionary<string, object> subDictioanry = new Dictionary<string, object>();

List<Dictionary<string, string>> subList = new List<Dictionary<string, string>>();

subList.Add(new Dictionary<string, string>(){
    {"valueLink", "link1"},
    {"valueTitle","title1"}
});
subList.Add(new Dictionary<string, string>(){
    {"valueLink", "link2"},
    {"valueTitle","title2"}
});
subList.Add(new Dictionary<string, string>(){
    {"valueLink", "link3"},
    {"valueTitle","title3"}
});

subDictioanry.Add("title", "title");
subDictioanry.Add("name", "name");
subDictioanry.Add("fieldname1", subList);

Dictionary<string, object> exitDictionary = new Dictionary<string, object>();
exitDictionary.Add("first", subDictioanry);
exitDictionary.Add("second", subDictioanry);
Run Code Online (Sandbox Code Playgroud)

在LINQ select的帮助下,是否可以获得所有"valueTitle"?

更新:对不起,我应该先写它 - 我需要从exitDictionary获得结果,而不是从subList

Ale*_*ici 21

如果您按fieldname1值搜索,请尝试以下操作:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .Where(d => d.ContainsKey("fieldname1"))
   .Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();
Run Code Online (Sandbox Code Playgroud)

如果您正在查看subDictionary(Dictionary<string, object>显式)中的值的类型,您可以这样做:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .SelectMany(d=>d.Values)
   .OfType<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();
Run Code Online (Sandbox Code Playgroud)

两种选择都将返回:

title1
title2
title3
title1
title2
title3
Run Code Online (Sandbox Code Playgroud)


Arr*_*ran 9

一种方法是先用以下方法展平列表SelectMany:

subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));
Run Code Online (Sandbox Code Playgroud)