Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract one column from a var using linq

i have something like this

var emp = db.Employees.toList();

in my employees table i have emp name, emp id and salary, using linq with lambda expressions, how do i access emp id in some another variable. I have tried looking up for it, couldn't find a solution which does it using linq with lambda expressions

var employeeLeaves = db.Leaves
     .Include("Employee")
     .Include("Employee.Manager")
     .Where(l => l.Status.Id == 1)
     .GroupBy(l => l.Employee.Manager.Id)
     .Select(l => l.GroupBy(k=>k.Employee.Id).Select(j=>j.GroupBy(‌​p=>p.GroupId)))
     .ToList(); 

this is the actual query i have,dont ask me how i wrote it..:P now i want to get id column from employeeLeaves and store it in some another variable

like image 437
Piyush Sardana Avatar asked May 15 '12 12:05

Piyush Sardana


1 Answers

It's not entirely clear what you're trying to do, which is why you've got so many answers with different approaches. If you're trying to turn the "collection of employees" into a "collection of IDs" then you want something like this:

var ids = emp.Select(x => x.Id);

Or more directly:

var ids = db.Employees.Select(x => x.Id);

(Optionally with ToList at the end of each of these.)

I would strongly advise you to learn LINQ (and the somewhat-related languages features such as var) thoroughly, from scratch, with the help of a good book or tutorial. Learning bits piecemeal by just finding samples which do something a bit like what you want is not a good approach, IMO.

like image 197
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet