Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .ToDictionary() extension method on DataRow

Tags:

c#

linq

I need a Dictionary<string,object> which is produced from a DataRow. I currently have something for this working, but I am doing way too much and not utilizing the .ToDictionary() extension method.

Can someone please enlighten me on how to accomplish this successfully?

Here is my failed attempt:

var dataDictionary = dataTable.Select(acn + "=" + accountNumber).ToDictionary(key => key.Table.Columns);

This returns a KeyValuePair<DataColumnCollection, DataRow>, but again, I need a Dictionary<string,object>

Thanks again in advance!

like image 609
BueKoW Avatar asked Jan 25 '11 20:01

BueKoW


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.

How do you initialize a DataRow?

To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.


2 Answers

I know this is old, but for those that come along later the correct LINQ expression is a slight modification of driis's code:

var dictionary = row.Table.Columns
    .Cast<DataColumn>()
    .ToDictionary(col => col.ColumnName, col => row.Field<string>(col.ColumnName));
like image 92
jjoelson Avatar answered Sep 21 '22 18:09

jjoelson


You need to specifiy the key you want, which might be the acn column in the table:

.ToDictionary(row => (string)row["acn"]);

ToDictionary takes a second delegate if you want to run a transformation on the values in the returned dictionary.

Edit

I'll leave the original answer since it explains the general case. You want to take a single row; then use it's columns as keys and the column values as the, well, values. This is how you do that.

 DataRow row = dataTable.Select(acn + "=" + accountNumber).Single(); // You might want SingleOrDefault
 var dataDictionary = row.Table.Columns.ToDictionary(col => col.Name, col => row[col.Name]);

Disclaimer, the above was written without a compiler at hand, might need a bit tweaking.

like image 33
driis Avatar answered Sep 18 '22 18:09

driis