LINQ字典中的字典
本文关键字:字典 LINQ | 更新日期: 2023-09-27 18:12:08
我要创建LINQ中与父id匹配的字典的字典。
有一个数据模型
Pseudo-Model:
Int ID;
Int Namel
Int? ParentID;
我想创建一个字典的字典。第一个Dictionary是那些只属于父类的对象的ID其中的字典将包含ID, Name。
我知道我可以通过循环来做到这一点,但我想弄清楚如何通过LINQ来做到这一点。
GroupBy
创建具有Key
值的IGrouping
,您可以迭代(或进行额外的LINQ调用)。
ToDictionary
接受两个选择器—一个用于键,一个用于值。外部字典的键为ParentID
,值为另一个字典的键为ID
,值为Name
。
假设ID
是唯一的(至少在ParentID
组中),您可以:
_model.Terrtories
.GroupBy(i => i.ParentID.HasValue ? i.ParentID.Value : 0)
.ToDictionary(g => g.Key, // outer dictionary key
g => g.ToDictionary(i => i.ID, // inner dictionary key
i => i.Name)); // inner dictionary value
请注意,外部ToDictionary
的第二个参数是将每个组中的项转换为内部字典。
我不知道你会怎么做,但这是它的样子。
var dict = new Dictionary<int, Dictionary<int,string>>()
{
{ 1, new Dictionary<int, string>()
{
{1, "Name1"},
{2, "Name2"},
{3, "Name3"},
}
},
{ 2, new Dictionary<int, string>()
{
{1, "Something1"},
{2, "Something2"},
{3, "Something3"},
}
},
};
如果你想表示一个父/子关系,为什么不创建一个父/子关系呢?
public class Parent
{
public int ID { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public int ID { get; set; }
public string Name { get; set; }
}