Sravan
Sravan

Reputation: 1135

How to filter the list using another list?

We have the following list of Employees.

List<Employee> EmployeeList =new List<Employee>();
EmployeeList.Add(new Employee{ Id=101, Name="XYZ" });
EmployeeList.Add(new Employee{ Id=102, Name="QRS" });
EmployeeList.Add(new Employee{ Id=103, Name="ABC" });
EmployeeList.Add(new Employee{ Id=1101, Name="DEF" });

And List of Selected Employee Id's as below.

List<long> selectedEmployeeIds={ 101,103 };

We wants to filter the selected Employees from the above EmployeeList. We tried using contains as below but its fetching 3 records as 101,102,1101.

var selectedEmployees= (from record in EmployeeList where selectedEmployeeIds.Contains(record.Id.ToString()) select record).ToList(); // returning 3 records.

Could any one help us to get only the Employees 101,103.

Thanks in Advance.

Upvotes: 0

Views: 103

Answers (2)

Sravan
Sravan

Reputation: 1135

Finally we got the result for the above query as,

List<Employee> filteredRecords = (from a in EmployeeList join b in selectedEmployeeIds on a.ID equals b select a).ToList();

Upvotes: 0

Habib
Habib

Reputation: 223257

You don't need ToString(), Use Enumerable.Contains, which will work with any datatype, not just strings. Your current code should give an error since selectedEmployeeIds is of type long and your are checking it against string.

var selectedEmployees= (from record in EmployeeList 
                       where selectedEmployeeIds.Contains(record.Id) 
                       select record).ToList();

Upvotes: 4

Related Questions