开发者

Linq: Convert datatable rows to Dictionary<string, Dictionary<string, string>>

I have a data table with columns "a", "b", "c". a and b are my lookup keys, and so I want to find c.

I'd like to use linq to convert it to a Dictionary<a, Dictionary<b, c>> (or an ILookup)

Is this possible?

The closet workaround I can come up with is:

var lookup = resultTable.AsEnumerable().ToLookup(row => row["a"] & row["b"], 
                   开发者_运维百科                            row => row["c"]);

and then I can concatenate a+b to use as the key.

Is there a better way, or is this possibly faster anyways due to it being a simpler data structure?


Here's one way you could do it in C#:

var dict = resultTable.AsEnumerable()
    .GroupBy(row => row.Field<A>("a"))
    .ToDictionary(
        g => g.Key,
        g => g.ToDictionary(
            row => row.Field<B>("b"),
            row => row.Field<C>("c")
        )
    );

And equivalent VB:

Dim dict = resultTable.AsEnumerable               
    .GroupBy(Function(row) row.Field(Of A)("a"))  
    .ToDictionary(                               
        Function(g) g.Key,                       
        Function(g) g.ToDictionary(              
            Function(row) row.Field(Of B)("b"),  
            Function(row) row.Field(Of C)("c")   
        )                                        
    )


Frankly, I think you should strive for a Dictionary<Tuple<A, B>, C>:

var dict = resultTable.AsEnumerable()
                      .GroupBy(row => Tuple.Create(
                                          row.Field<A>("a"), 
                                          row.Field<B>("b")
                                      )
                      )
                      .ToDictionary(
                          group => group.Key,
                          group => group.Single().Field<C>("c")
                      );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜