Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DataTable to LINQ Anonymous Type

Tags:

c#

linq

datatable

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.

like image 232
Abdul Rehman Sayed Avatar asked Dec 19 '22 06:12

Abdul Rehman Sayed


1 Answers

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));
like image 80
Parthasarathy Avatar answered Jan 04 '23 21:01

Parthasarathy