Linq expression to convert a DataTable to a dictionary <Key, List <Values ​​>>

I am trying to convert DataTable forms

Key  Value
1    A
1    B
1    C
2    X
2    Y

To the dictionary

1 [A,B,C]
2 [X,Y]

The yambda expression that I use

GetTable("..sql..").AsEnumerable().
    .Select(r => new {Key = r.Field<int>("Key"), Val = r.Field<string>("Value")})
    .GroupBy(g => g.Key)
    .ToDictionary(a => a.Key, a => String.Join(",", a.Value))

But it fails with "Cannot convert lambda expression to type" System.Collections.Generic.IEqualityComparer "because it is not a delegate type"

How can i do this?

+4
source share
3 answers

It does:

GetTable("..sql..").AsEnumerable().
    .Select(r => new {Key = r.Field<int>("Key"), Val = r.Field<string>("Value")})
    .GroupBy(g => g.Key)
    .ToDictionary(a => a.Key, a => String.Join(",", a.Select(x => x.Value).ToList()))
+4
source
var foo = GetTable("").AsEnumerable()
                 .ToLookup(x => x.Key, x => x.Value);
foreach(var x in foo)
{
    foreach(var value in x)
    {
        Console.WriteLine(string.Format("{0} {1}", x.Key, value));
    }

}
+1
source

Here is another way you can do this ...

GetTable("..sql..").AsEnumerable()
    .GroupBy(x => x.Field<int>("Key"))
    .ToDictionary(grp => grp.Key, x => x.Select(y => y.Field<string>("Value")).ToList());
0
source

Source: https://habr.com/ru/post/1525725/


All Articles