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!
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.
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.
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));
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.
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.
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