23 November 2011

LINQ - On DataTable

You can transform a DataTable into a List of objects in a single statement using LINQ:
List<Customer> list = (from r in dataTable.AsEnumerable()
                       select new Customer {
                         Id      = r.Field<int>("Id"),
                         Name    = r.Field<string>("Name"),
                         Created = r.Field<datetime>("Created")
                       }).ToList();

To use AsEnumerable, you need to reference the assembly System.Data.DataSetExtensions (.NET 3.5) or include System.Data (.NET 4.5).

No comments:

Post a Comment