NShaik NShaik - 18 days ago 6
JSON Question

How to convert a datatable to dictionary<string, list<object>> in C#?

I have a datatable like this

ID CategoryID Category
1 1 Category1
2 1 Category2


and I am trying to generate keyed json like this

{
"1"
[
{Category: Category1},
{Category:Category2}
]
}


How can I covert my datatable to
dictionary<string, list<object>>
so that I can serialize it with
JSON.NET

Yes running in to duplicate key issues with dictionary.
Thanks in advance for any ideas.

Answer

Here full code:

var dataTable = new DataTable();

dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("CategoryID", typeof(int));
dataTable.Columns.Add("Category", typeof(string));

dataTable.Rows.Add(1, 1, "Category1");
dataTable.Rows.Add(2, 1, "Category2");
dataTable.Rows.Add(3, 2, "Category3");
dataTable.Rows.Add(4, 2, "Category4");
dataTable.Rows.Add(5, 1, "Category5");
dataTable.Rows.Add(6, 3, "Category6");


var dict = dataTable.AsEnumerable()
    .GroupBy(row => row.Field<int>("CategoryID"))
    .ToDictionary(
        g => g.Key.ToString(),
        g => g.Select(row => new { Category = row.Field<string>("Category") }).ToList()
    );

var jss = new JavaScriptSerializer();
Console.WriteLine(jss.Serialize(dict));

Last string gives you json (I formatted it for better readability):

{
  "1":
        [
          {"Category":"Category1"},
          {"Category":"Category2"},
          {"Category":"Category5"}
        ],
  "2":
        [
          {"Category":"Category3"},
          {"Category":"Category4"}
        ],
  "3":
        [
          {"Category":"Category6"}
        ]
}
Comments