如何使用LINQ将数据表转换为C#中的强类型对象列表? [英] How to convert a data table to a list of strongly typed objects in C# using LINQ?

查看:49
本文介绍了如何使用LINQ将数据表转换为C#中的强类型对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#代码编写的WPF应用程序,我的问题是我需要从数据集中转换数据表,但可悲的是,它引发了异常" 无法将lambda表达式转换为'string'类型因为它不是委托类型 "",请帮我解决这个问题.(我有抛出异常的代码)

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

推荐答案

使用 AsEnumerable Field<T> :

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

这篇关于如何使用LINQ将数据表转换为C#中的强类型对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆