DataTable. DataTable into a JSON object.
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