21

I need to convert DataRow into Dictionary using LINQ.

The code below will get the DataRow, the next step is I need convert it to dictionary(ColumnName, RowVale)

var WorkWeekData = from data in mWorkWeekData.AsEnumerable ()
            where data.Field<string> ("Code") == code
            select data;
QKWS
  • 1,069
  • 9
  • 22
  • 41

2 Answers2

46

It's definitely possible, yes:

var dict = row.Table.Columns
              .Cast<DataColumn>()
              .ToDictionary(c => c.ColumnName, c => row[c]);
Rob
  • 26,989
  • 16
  • 82
  • 98
1

You 'can' use this approach but when I tried it, hoping to improve performance, I found it was MUCH slower than using the longer solution.

This way:

foreach (DataRow row in dtIn.Rows)
{
    dictionary.Clear();
    foreach (DataColumn dataColumn in dtIn.Columns)
    {
        dictionary.Add(dataColumn.ColumnName, row[dataColumn.ColumnName].ToString());
    }
}

Is much faster than:

foreach (DataRow row in dtIn.Rows)
{
    dictionary = row.Table.Columns.Cast<DataColumn>()
        .ToDictionary(c => c.ColumnName, c => row[c].ToString());
}
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
Skattch
  • 11
  • 1
  • Just a note that you need to account for nullable columns as well. .ToString() will throw an error if your value is DBNull. – Storm Aug 03 '22 at 09:39