Convert datatable to JSON in C#

后端 未结 17 1404
猫巷女王i
猫巷女王i 2020-11-22 11:53
  1. I want to get records from database into a DataTable.
  2. Then convert the DataTable into a JSON object.
  3. Return the JSON ob
17条回答
  •  生来不讨喜
    2020-11-22 12:48

    This has similar approach to the accepted answer, but uses LINQ to convert datatable to list in a single line of code.

    //convert datatable to list using LINQ. Input datatable is "dt", returning list of "name:value" tuples
    var lst = dt.AsEnumerable()
        .Select(r => r.Table.Columns.Cast()
                .Select(c => new KeyValuePair(c.ColumnName, r[c.Ordinal])
               ).ToDictionary(z=>z.Key,z=>z.Value)
        ).ToList();
    //now serialize it
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    return serializer.Serialize(lst);
    

    This is an incredibly useful way to enumerate a datatable, which would normally take a ton of coding! Here are some variations:

    //convert to list with array of values for each row
    var list1 = dt.AsEnumerable().Select(r => r.ItemArray.ToList()).ToList();
    
    //convert to list of first column values only
    var list2 = dt.AsEnumerable().Select(r => r.ItemArray[0]).ToList();
    
    // parse a datatable with conditions and get CSV string
    string MalesOver21 = string.Join(",",
        dt.AsEnumerable()
          .Where(r => r["GENDER"].ToString()=="M" && r.Field("AGE")>21)
          .Select(r => r.Field("FULLNAME"))
     );
    

    This is off topic to the original question but for completeness sake, I'd mention that if you just want to filter out rows from an existing datatable, See this answer

提交回复
热议问题