How to convert a data table to a list of strongly typed objects in C# using LINQ?

 

Questions


I am doing a WPF Application written with C# code, My problem is I need to convert a data table from a dataset but sadly it throws me the exception “Cannot convert lambda expression to type ‘string’ because it is not a delegate type” can you guys please help me with this.(I had the code which throws me the exception)

        SqlDataAdapter da = new SqlDataAdapter(commBuildingSelector);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataTable myTable = ds.Tables[0];
        List<Building> buildings = new List<Building>();
        buildings = (from bl in myTable
                    select new Building()
                    {
                        BuildingID = bl.BuildingID,
                        BuildingName = bl.BuildingName,
                        isActive = bl.isActive,
                        LastEditDate = bl.LastEditDate,
                        LastEditUser = bl.LastEditUser
                    }).ToList();
        return new List<Building>();

 

 

————————————————-

Answer

Use AsEnumerable and Field<T>:

buildings = (from bl in myTable.AsEnumerable()
             select new Building()
             {
                 BuildingID = bl.Field<int>("BuildingID")
                 // etc
             }).ToList();

linq

Facebook Comments

Post a comment