Convert DataTable to LINQ Anonymous Type
c#, datatable, linq
Solution
Since the property names are not known at compile time and you want to use the data for JSON serialization, you can use the following to create a list of dictionary. If you use Newtonsoft JSON, then the serialization takes care of converting the key value pairs in a JSON object format.
IEnumerable<Dictionary<string,object>> result = dt.Select().Select(x => x.ItemArray.Select((a, i) => new { Name = dt.Columns[i].ColumnName, Value = a })
.ToDictionary(a => a.Name, a => a.Value));
Problem
I want a function which takes in a datatable & returns a List (object is not DataRow) Eg. : I know I can do this (but this requires column names to be known) : ``` // Datatable dt = Filled from a Database query & has 3 columns Code,Description & ShortCode List<object> rtn = new List<object>(); var x = from vals in dt.Select() select new { Code = vals["Code"], Description = vals["Description"], ShortCode = vals["ShortCode"], }; rtn.AddRange(x) return rtn; ``` What i want is a generic version so that i can pass in any datatable & it will generate based on column names in the datatable.