Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda where condition in Join statement [closed]

Tags:

c#

lambda

linq

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 .Where Clause 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

like image 992
Eldho Avatar asked Oct 28 '25 09:10

Eldho


1 Answers

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();
like image 168
Gilad Green Avatar answered Oct 29 '25 23:10

Gilad Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!