如何使用lambda表达式将DataTable记录放入列表中?

时间:2016-05-26 10:03:23

标签: c# asp.net-mvc model-view-controller

在给定的代码中,我编写了lambda表达式,但它显示了一个错误 - 无法将lambda表达式转换为类型'string',因为它不是委托类型。

        EmployeeDataOperation emp = new EmployeeDataOperation(); //Class to perform CRUD operation.

        List<EmployeeProp> data = new List<EmployeeProp>();

        dt = emp.getEmployeeData();//return datatable with records.

        //I want to use lambda expression to use Datatable data as a list
        data = (from a in dt
                select new EmployeeProp { Name = a.Name, Email = a.Email }).ToList();
        //error near select

        return View(data);

3 个答案:

答案 0 :(得分:3)

您可以使用.Field linq扩展名或索引/列名称(前行[“columnname”]来访问DataRow中的值。我建议使用Field扩展名,因为它甚至可以处理nullable种类型。

data  = dt.AsEnumerable()
  .Select(row=>  new EmployeeProp ()
   {
       Name = row.Field<string>("Name"),
       Email = row.Field<string>("Email ") 
       // Other properties....      
   })
   .ToList();

答案 1 :(得分:0)

 var myData = (from a in dt.AsEnumerable()
               select new EmployeeProp { 
                   Name = a.Field<string>("Name"), 
                   Email = a.Field<string>("Email") 
              }).ToList();

答案 2 :(得分:0)

您也可以尝试这样做,制作EmployeeProp()对象

data = (from a in dt
                select new EmployeeProp() { Name = a.Name, Email = a.Email }).ToList();