1

In given code I have written lambda expression but it shows an error that -- Can't convert lambda expression to type 'string' because it is not a delegate type.

        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);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Ankit Modi
  • 25
  • 1
  • 9

3 Answers3

5

You could use either .Field linq extension or index/columnname (ex row["columnname"] to access values from a DataRow. I suggest using Field extension as it even handle nullable types.

data  = dt.AsEnumerable()
  .Select(row=>  new EmployeeProp ()
   {
       Name = row.Field<string>("Name"),
       Email = row.Field<string>("Email ") 
       // Other properties....      
   })
   .ToList();
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0
 var myData = (from a in dt.AsEnumerable()
               select new EmployeeProp { 
                   Name = a.Field<string>("Name"), 
                   Email = a.Field<string>("Email") 
              }).ToList();
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
  • I just want to try, otherwise, I am using entity framework which will return DbSet<> and easily convert into a list. – Ankit Modi May 26 '16 at 10:13
  • I missed that you had new EmployeeProp {}. So it would be a List. Yes, a DbSet would be much cleaner and easier, doesn't need this cumbersome string syntax and provides intellisense on fields. If the source is something like MS SQL, MySQL, Sqlite ... then you might as well use Linq To SQL too instead of Linq to EF. – Cetin Basoz May 26 '16 at 10:16
0

you can try this too, make EmployeeProp() object

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