Linq - Transform DataTable to Dictionary using C#

21 July 2022 | Viewed 7972 times

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.

Namespace: System.Collections.Generic

The generic method ToDictionary has 3 parameters <DataRow, string, object>.

C# Code
Dictionary<string, string> dict = ds.Tables[0].AsEnumerable()
.ToDictionary<DataRow, string, string>(
row => row.Field<string>("COLUMN1"),
row => row.Field<string>("COLUMN2"));


Now the dictionary has COLUMN1 as "Key" and COLUMN2 as "Value".

The Dictionary<TKey,TValue> generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<TKey,TValue> class is implemented as a hash table.

PreviousNext