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?
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.
There are the following 3 ways to convert a DataTable to a List. Using a Loop. Using LINQ. Using a Generic Method.
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.
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()))
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With