Reputation: 1425
I have a data collection of type IEnumerable<Objects.LabourHours>
containing labour records for various employees. I wish to filter the list and return only records for selected employees, which is specified by a list of int[] employees
containing the EmployeeID
s.
class LabourHours
{
public int ID {get;set;}
public int EmployeeID {get;set;}
public int HoursWorked {get;set;}
}
How would I go about this? I am sure this has been asked before but I can't find anything similar on here. The closest I have found involves grouping the records by UserID, which is not what I need - I need the actual records.
Upvotes: 14
Views: 27129
Reputation: 1
If you want the result to preserve the order of the employees
array, you can use Select
on the array. From the doc, it "Projects each element of a sequence into a new form", which is basically what you'd want to do in this case.
var result = employees.Select(e => labourHours.First(l => l.EmployeeID == e));
Use FirstOrDefault
if all employees
don't necessarily have an associated labourHours
entry.
Upvotes: 0
Reputation: 75326
You can filter your list with LINQ Where
using Contains
method:
var result = list.Where(x => employees.Contains(x.EmployeeID));
Upvotes: 26