如何使用LINQ将数据表转换为C#中强类型对象的列表?

时间:2011-10-08 00:35:39

标签: linq

我正在使用C#代码编写WPF应用程序,我的问题是我需要从数据集转换数据表但遗憾的是它抛出异常“ 无法将lambda表达式转换为类型'string'因为它不是委托类型 “你们可以帮我解决这个问题吗。(我的代码会引发异常)

        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>();

1 个答案:

答案 0 :(得分:4)

使用AsEnumerableField<T>

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