简体   繁体   English

如何将数据表转换为字典 <string, list<object> &gt;在C#中?

[英]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 我正在尝试生成这样的键控json

    {
     "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. 如何将我的数据表隐藏到dictionary<string, list<object>>以便可以使用JSON.NET对其进行序列化JSON.NET是,可以复制字典中的关键问题。 Thanks in advance for any ideas. 预先感谢您的任何想法。

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): 最后一个字符串为您提供json(为了方便阅读,我对其进行了格式化):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM