Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform a DataTable into Dictionary C#

I want to know how to transform a DataTable into a Dictionary. I did something like this.

using System.Linq;  internal Dictionary<string,object> GetDict(DataTable dt) {     return dt.AsEnumerable()       .ToDictionary<string, object>(row => row.Field<string>(0),                                 row => row.Field<object>(1)); } 

But I get:

System.Data.EnumerableRowCollection does not contains a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Parallel.Enumerable.ToDictionary(System.Linq.ParallelQuery, System.Func, System.Collections.Generic.IEqualityComrparer)' has some invalid argumentsch

How can I resolve this?

Thanks

like image 763
Maximus Decimus Avatar asked Oct 31 '13 17:10

Maximus Decimus


People also ask

How do you convert a data table to a dictionary?

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.

Does Web services support data table?

Solution 4You can return DataTable in WebService. You just need to give full DataTable name. DataTable dt = new DataTable("YourTableName"); That's all.


2 Answers

The generic method ToDictionary has 3 parameters. You left one off, so it doesn't know what to do. If you want to specify all of the parameters, it would be <DataRow, string, object>.

internal Dictionary<string,object> GetDict(DataTable dt) {     return dt.AsEnumerable()       .ToDictionary<DataRow, string, object>(row => row.Field<string>(0),                                 row => row.Field<object>(1)); } 

Of course, if you leave them off, the compiler is able to infer the types, so you don't get the error.

like image 147
cadrell0 Avatar answered Sep 20 '22 10:09

cadrell0


All the previos answers didn't help me, so I did this:

myList = dt.AsEnumerable() .ToDictionary<DataRow, string, string>(row => row[0].ToString(),                                        row => row[1].ToString());  

and it worked great!

like image 25
ParPar Avatar answered Sep 19 '22 10:09

ParPar