[英]How can i select all values from a nested dictionary with linq?
我的Super
属性是
public List<Test> Super { get; set; }
而我的Test
课程是
public class Test
{
public int Id { get; set; }
public Dictionary<string, string> dict { get; set; }
}
如何从字典中选择键名称为"description"
所有值
您可以使用SelectMany
获取所有词典,例如:
var values = Super
.SelectMany(s => s.dict)
.Where(s => s.Key == "description")
.Select(s => s.Value);
你可以做点什么
var dict = (from p in obj.Super
where p.dict != null && p.dict.ContainsKey(keyToCheck)
select p.dict[keyToCheck]);
完整代码:
void Main()
{
string keyToCheck = "description";
var obj = new Super1();
var dict = (from p in obj.Super
where p.dict != null && p.dict.ContainsKey(keyToCheck)
select p.dict[keyToCheck]);
Console.Write(dict);
}
public class Super1
{
public List<Test> Super { get; set; } = new List<Test>(){
new Test(){ Id = 1, dict = new Dictionary<string,string>() {
{"description","abc"},{"description1","1"},{"description2","2"},{"description3","3"}
}},
new Test(){ Id = 2, dict = new Dictionary<string,string>() {
{"description","xyz"},{"description4","4"},{"description5","5"},{"description6","6"}
}
}};
}
public class Test
{
public int Id { get; set; }
public Dictionary<string, string> dict { get; set; }
}
输出:
abc
xyz
你可以试试
List<string> AllValues = new List<string>();
Super.ForEach(x =>
{
if(x.dict.ContainsKey("description")
{
AllValues.AddRange(x.dict["description"]);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.