Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Expression to Turn DataTable to Dictionary of <Key, List<Values>>

Tags:

c#

linq

I am trying to convert a DataTable of the form

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

To a Dictionary

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

The lambda expression I am using is

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 accomplish this?

like image 918
Ryan Avatar asked Feb 07 '14 02:02

Ryan


People also ask

How to convert DataTable to Dictionary in c# using LINQ?

When we need to transform 2 columns of data table to a dictionary, we can use LINQ. Dictionary is a Key Value Pair collection and Key should be unique. You can create the Dictionary<TKey, TValue> object by passing the type of keys and values it can store.

Can we convert DataTable to list?

There are the following 3 ways to convert a DataTable to a List. Using a Loop. Using LINQ. Using a Generic Method.

What is AsEnumerable in C#?

AsEnumerable() in C# It is an extension method. The following is our array − int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; Now, get the IEnumerable equivalent.


2 Answers

This does it:

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()))
like image 125
Ryan Avatar answered Sep 28 '22 06:09

Ryan


Here's another way you can do it...

GetTable("..sql..").AsEnumerable()
    .GroupBy(x => x.Field<int>("Key"))
    .ToDictionary(grp => grp.Key, x => x.Select(y => y.Field<string>("Value")).ToList());
like image 41
MrBlue Avatar answered Sep 28 '22 06:09

MrBlue