C# 如何使用linq从嵌套字典中选择所有值?
我的C# 如何使用linq从嵌套字典中选择所有值?,c#,linq,C#,Linq,我的Super类属性为 public List<Test> Super { get; set; } 如何从关键字名称为“description”的字典中选择所有值?您可以使用SelectMany获取所有字典,例如: var values = Super .SelectMany(s => s.dict) .Where(s => s.Key == "description") .Select(s => s.Value); 你可以试试 List
Super
类属性为
public List<Test> Super { get; set; }
如何从关键字名称为“description”的字典中选择所有值?您可以使用
SelectMany
获取所有字典,例如:
var values = Super
.SelectMany(s => s.dict)
.Where(s => s.Key == "description")
.Select(s => s.Value);
你可以试试
List<string> AllValues = new List<string>();
Super.ForEach(x =>
{
if(x.dict.ContainsKey("description")
{
AllValues.AddRange(x.dict["description"]);
}
});
List AllValues=new List();
Super.ForEach(x=>
{
如果(x.dict.ContainsKey(“说明”)
{
AllValues.AddRange(x.dict[“description”]);
}
});
您可以执行以下操作
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; }
}
不过,混合使用Linq fluent和查询语法有点尴尬。从lambdata中删除此操作不使用字典的O(1)查找。
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