How to use .ToDictionary() extension method on DataRow
I nee开发者_运维问答d 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!
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.
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.
@jjoelson's answer produces a Dictionary<string, string>
. If you want a Dictionary<string, object>
, you could, of course, do:
var dictionary = row.Table.Columns
.Cast<DataColumn>()
.ToDictionary(col => col.ColumnName, col => row.Field<object>(col.ColumnName));
But a slightly less convoluted version is:
var dictionary row.Table.Columns
.Cast<DataColumn>()
.ToDictionary(col => col.ColumnName, col => row[col]);
I like LINQ
dataTable.Rows.Cast<DataRow>().Select(e=>e.Table.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => e[col.ColumnName]) ).ToList()
精彩评论