Home > Mobile >  How to transform DataTable.Rows into a List of Dictionary<T1, T2> in C#, .Net Core
How to transform DataTable.Rows into a List of Dictionary<T1, T2> in C#, .Net Core

Time:11-27

Suppose, we've below demo datasets:

var demoDatasets = new DataTable
{
  Columns = {
              { "ID", typeof(int) },
              { "Name", typeof(string) },
              { "Address", typeof(string) }
  },
  Rows = {
           { 1, "A", "AddressA1" },
           { 2, "B", "AddressB1" },
           { 3, "C", "AddressC1" }
         }
};

Now, I want transfer this DataTable into a Dictionary List corresponds with both columns and rows.

CodePudding user response:

First, take a Lists of Dictionary for storing all your datum into:

List<Dictionary<string, object>> databanks = new();

Then, bring up a loop for taking every single row and transform in a dictionary along with corresponding columns:

foreach (DataRow dr in demoDatasets.Rows)
{
  var dictionary = dr.Table.Columns.Cast<DataColumn>()
                     .ToDictionary(col => col.ColumnName, col => (dr[col.ColumnName] == DBNull.Value)
                       ? string.Empty
                       : dr[col.ColumnName]);

  databanks.Add(dictionary);
}

CodePudding user response:

If you are looking for this result

{"ID":[1,2,3],"Name":["A","B","C"],"Address":["AddressA1","AddressB1","AddressC1"]}

the following code can help you

var dict = new Dictionary<string, List<object>>(demoDatasets.Rows.Count);

foreach (DataRow row in demoDatasets.Rows)
{
    for (var i = 0; i < demoDatasets.Columns.Count; i  )
    {
        var cellValue = row[i];
        var name = demoDatasets.Columns[i].ColumnName;
        if (dict.TryGetValue(name, out var list))
        {
            list.Add(cellValue);
        }
        else
        {
            dict.Add(name, new List<object>(demoDatasets.Columns.Count) { cellValue });
        }
    }
}
  • Related