I have to filter Employee based on their department. I'm able to do the same with LINQ.
Linq and lambda compile to get same result. The compiler changes the query expression into the equivalent Lambda expression before compiling it, so the generated IL is exactly the same.Source
var deptCollection = new List<Dept>();
var employeeCollection = new List<Employee>();
employeeCollection.Add(new Employee { Id = 1, Name = "Eldho" });
deptCollection.Add(new Dept { DepetarmentName = "a", EmployeeId = 3 });
deptCollection.Add(new Dept { DepetarmentName = "a", EmployeeId = 1 });
var empinadept = (from e in employeeCollection
from dep in deptCollection
where e.Id == dep.EmployeeId
&& dep.DepetarmentName == "a"
select e)
.ToList();
I can't able to add
.WhereClause in this lambda
var empindeptLamda = employeeCollection
.Join(deptCollection,
emp => emp.Id, dep => dep.EmployeeId,
(em, dep) => em.Id == dep.EmployeeId
&& dep.DepetarmentName == "a")
.ToList();
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
class Dept
{
public int EmployeeId { get; set; }
public string DepetarmentName { get; set; }
}
Q1. What is the equivalent lambda statement for the above linq ? (How to add where clause as in linq in method-syntax
The equivalent for this:
var empinadept = (from e in employeeCollection
from dep in deptCollection
where e.Id == dep.EmployeeId
&& dep.DepetarmentName == "a"
select e)
.ToList();
Is this:
var result = employeeCollection.Join(deptCollection,
e => e.Id,
dep => dep.EmployeeId,
(e,dep) => new { e, dep })
.Where(item => item.dep.DepetarmentName == "a")
.Select(item => item.e)
.ToList();
A better option will be to:
var result = employeeCollection.Join(
deptCollection.Where(dep => dep.DepetarmentName == "a"),
e => e.Id,
dep => dep.EmployeeId,
(e,dep) => e)
.ToList();
Closest to the query-syntax (but I would say that is less nice opinion based) is:
var result = employeeCollection.Join(
deptCollection,
e => new { e.Id, "a" },
dep => new { dep.EmployeeId, dep.DepartmentName },
(e,dep) => e).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With