I have a datatable like this:
Column1 | Column2 | Column3 |
---|---|---|
Name1 | Code111 | 12550 |
Name2 | Code112 | 12551 |
Name3 | Code113 | 12552 |
Name4 | Code114 | 12553 |
I want to convert it to a dictionary where the first column is the key. The combination of the second column with lowercase letters and the third column is the value.
Expected result:
key | value |
---|---|
Name1 | code111_12550 |
Name2 | code112_12551 |
Name3 | code113_12552 |
Name4 | code114_12553 |
This is my code:
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
dt.Columns.Add("Column3");
dt.Rows.Add("Name1", "Code111", 12550);
dt.Rows.Add("Name2", "Code112", 12551);
dt.Rows.Add("Name3", "Code113", 12553);
dt.Rows.Add("Name4", "Code114", 12554);
Dictionary<string,string> dic = new Dictionary<string,string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
string _k = dt.Rows[i][0].ToString();
string _v = dt.Rows[i][1].ToString().ToLower()+ "_" +
dt.Rows[i][2].ToString();
dic.Add(_k, _v);
}
Is there a better way to convert a datatable to a dictionary? For example, can I use Linq?
2
Answers
You can use the linq.enumerable.todictionary to convert the
DataTable
into aDictionary
:Since .NET 6 is the oldest supported .NET Core version, one can use ranges to reduce the code to this :
If the values need to be lowercase,
ToLower()
can be called after joining.