Convert complex hierarchical Datatable to json in c#

Convert complex hierarchical Datatable to json in c#

using System;
using System.Linq;
using System.Data;
using System.Data.DataSetExtensions;
using System.Collections.Generic;
using System.Xml;
using Newtonsoft.Json;
					
public class Program
{
	public static void Main()
	{
		DataTable dt = new DataTable();
                dt.Columns.Add("Name", typeof(string));
                dt.Columns.Add("Address", typeof(string));
                AddRow(dt, "companies", "addresses");
                AddRow(dt, "companies", "location");
                var result = dt.AsEnumerable().GroupBy(x => x.Field<string>("Name"))
                                          .Select(x => new
                                          {
                                              Name = x.Key,
                                              Address = x.Where(z => z.Field<string>("Address") != null)
                                                         .Select(z => z.Field<string>("Address")).ToList()
                                          });

            string jsonResult = JsonConvert.SerializeObject(result);
            Console.WriteLine(jsonResult);
	}
	
	private static void AddRow(DataTable dt,string name, object add)
        {
            DataRow row = dt.NewRow();
            row["Name"] = name;
            row["Address"] = add;
            dt.Rows.Add(row);
        }
}

Result:-

[{"Name":"companies","Address":["addresses","location"]}]

2020-02-21