如何创建字典的字典...?
How to create a dictionary of dictionaries...?
假设我有一个数据库,其中有一个或多个 table 以及一个或多个列的索引...
我想创建并填充 Dictionary<string, Dictionary<string, List<string>>>
,这样我就可以获得特定 table 的所有索引或 table 和索引的特定组合的所有列。
这里是带有 table、索引和列名的元组(示例数据)
List<Tuple<string, string, string>> tuples = new List<Tuple<string, string, string>>();
tuples.Add(Tuple.Create("T1", "I1", "C1"));
tuples.Add(Tuple.Create("T1", "I1", "C2"));
tuples.Add(Tuple.Create("T1", "I1", "C3"));
tuples.Add(Tuple.Create("T1", "I2", "C1"));
tuples.Add(Tuple.Create("T2", "I1", "C1"));
tuples.Add(Tuple.Create("T3", "I1", "C1"));
tuples.Add(Tuple.Create("T3", "I1", "C2"));
tuples.Add(Tuple.Create("T3", "I2", "C1"));
tuples.Add(Tuple.Create("T3", "I2", "C2"));
tuples.Add(Tuple.Create("T3", "I2", "C3"));
我能想到的最好的是:
Dictionary<string, Dictionary<string, List<string>>> perTI = new Dictionary<string, Dictionary<string, List<string>>>();
foreach (var group in tuples.GroupBy(x => Tuple.Create(x.Item1, x.Item2)))
{
perTI[group.Key.Item1] = new Dictionary<string, List<string>>(){ { group.Key.Item2, group.Select(g => g.Item3).ToList() } };
}
有谁知道用 1 个 LINQ 语句来完成的方法吗?
全部在一行中,如果这是您想要的:
Dictionary<string, Dictionary<string, List<string>>> dict =
new List<Tuple<string, string, string>>().GroupBy(item => item.Item1)
.ToDictionary(
groupedByItem1 => groupedByItem1.Key,
groupedByItem1 =>
groupedByItem1.GroupBy(item => item.Item2)
.ToDictionary(
groupedByItem2 => groupedByItem2.Key,
groupedByItem2 => groupedByItem2.Select(item => item.Item3).ToList()));
假设我有一个数据库,其中有一个或多个 table 以及一个或多个列的索引...
我想创建并填充 Dictionary<string, Dictionary<string, List<string>>>
,这样我就可以获得特定 table 的所有索引或 table 和索引的特定组合的所有列。
这里是带有 table、索引和列名的元组(示例数据)
List<Tuple<string, string, string>> tuples = new List<Tuple<string, string, string>>();
tuples.Add(Tuple.Create("T1", "I1", "C1"));
tuples.Add(Tuple.Create("T1", "I1", "C2"));
tuples.Add(Tuple.Create("T1", "I1", "C3"));
tuples.Add(Tuple.Create("T1", "I2", "C1"));
tuples.Add(Tuple.Create("T2", "I1", "C1"));
tuples.Add(Tuple.Create("T3", "I1", "C1"));
tuples.Add(Tuple.Create("T3", "I1", "C2"));
tuples.Add(Tuple.Create("T3", "I2", "C1"));
tuples.Add(Tuple.Create("T3", "I2", "C2"));
tuples.Add(Tuple.Create("T3", "I2", "C3"));
我能想到的最好的是:
Dictionary<string, Dictionary<string, List<string>>> perTI = new Dictionary<string, Dictionary<string, List<string>>>();
foreach (var group in tuples.GroupBy(x => Tuple.Create(x.Item1, x.Item2)))
{
perTI[group.Key.Item1] = new Dictionary<string, List<string>>(){ { group.Key.Item2, group.Select(g => g.Item3).ToList() } };
}
有谁知道用 1 个 LINQ 语句来完成的方法吗?
全部在一行中,如果这是您想要的:
Dictionary<string, Dictionary<string, List<string>>> dict =
new List<Tuple<string, string, string>>().GroupBy(item => item.Item1)
.ToDictionary(
groupedByItem1 => groupedByItem1.Key,
groupedByItem1 =>
groupedByItem1.GroupBy(item => item.Item2)
.ToDictionary(
groupedByItem2 => groupedByItem2.Key,
groupedByItem2 => groupedByItem2.Select(item => item.Item3).ToList()));