Convert DataTable to multi dimentional Array using Linq in ASP.Net

Last Reply 5 months ago By sanjay8090

Posted 5 months ago

I have some code for convert table to json

want to remove all loop with the help of linq

any way to convert foreach to linq

how does i do

        static public string table2Json(DataSet ds, int table_no)
        {
            try
            {
                // Given a Dataset & Table NO , function returns a 2 dim JSON Array of values in that table                        
                int rcnt = ds.Tables[table_no].Rows.Count; // Row Count
                int ccnt = ds.Tables[table_no].Columns.Count; // Col Count


                object[][] tb = new object[rcnt][];

                int r = 0;
                foreach (DataRow dr in ds.Tables[table_no].Rows)
                {
                    tb[r] = new object[ccnt];
                    for (int col = 0; col < ccnt; col++)
                    {
                        tb[r][col] = dr[col];

                        if ((tb[r][col]).Equals(System.DBNull.Value))
                            tb[r][col] = "";
                    }
                    r++;
                }
                //JavaScriptSerializer js = new JavaScriptSerializer();
                // return js.Serialize(tb);
                var table= JsonConvert.SerializeObject(tb); //change by sanjay 15/10/2019 using newtonsoft json
                return table;
            }
Posted 5 months ago

I have done this already and right Answer is given below

static public string table2Json(DataSet ds, int table_no)
{ 
    try
    {             
        var tb = ds.Tables[table_no].Rows.Cast<DataRow>().AsEnumerable()
            .Select(r => r.ItemArray.Select(c => c == DBNull.Value ? "" : c).ToArray())
            .ToArray();
               
        return JsonConvert.SerializeObject(tb);
    }
    catch (Exception ex)
    {
        tools.log(ex.Message);
        throw ex;
    }           
}