如何创建字典词典......?

时间:2015-06-24 15:16:07

标签: c# linq linq-to-objects

想象一下,我有一个包含一个或多个表的数据库,还有一个或多个列的索引......

我想创建并填充Dictionary<string, Dictionary<string, List<string>>>,以便我可以获取特定表的所有索引或表和索引的特定组合的所有列。

这里包含表,索引和列名称(样本数据)的元组

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语句做到这一点的方法?

1 个答案:

答案 0 :(得分:1)

全部在一行中,如果这是你想要的:

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()));