How to create a dictionary of dictionaries...?

147 views Asked by At

Imagine I have a database with one or more tables with one more indexes with one or more columns...

I want to create and fill a Dictionary<string, Dictionary<string, List<string>>> so I can get all indexes of a specific table or all the columns of a specific combination of a table and an index.

Here the tuples with the table, index and column names (sample data)

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

Best I could come up with is this:

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

Does anyone know a way to do it with 1 LINQ statement?

1

There are 1 answers

0
Jon G On BEST ANSWER

All in one line, if that's what you'd like:

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