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?
CodePudding user response:
You can use the linq.enumerable.todictionary to convert the DataTable
into a Dictionary
:
var _dic = dt.AsEnumerable()
.ToDictionary<DataRow, string, string>(row => row.Field<string>(0),
row => row.Field<string>(1).ToLower() "_" row.Field<string>(2) );
CodePudding user response:
Since .NET 6 is the oldest supported .NET Core version, one can use ranges to reduce the code to this :
var dict=dt.AsEnumerable().ToDictionary(
r=>r[0],
r=>String.Join('_',r.ItemArray[1..]));
If the values need to be lowercase, ToLower()
can be called after joining.
var dict=dt.AsEnumerable().ToDictionary(
r=>r[0],
r=>String.Join('_',r.ItemArray[1..])?.ToLower());