关于C#:Lambda Join语句中的条件

Lambda where condition in Join statement

我必须根据其department过滤Employee。 我可以使用LINQ进行相同的操作。

Linqlambda进行编译以获得相同的结果。 编译器在编译查询表达式之前将查询表达式更改为等效的Lambda expression,因此生成的IL完全相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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。 上面的linq的等效lambda语句是什么? (如何在方法语法中的linq中添加where子句


与此等效:

1
2
3
4
5
6
var empinadept = (from e in employeeCollection
              from dep in deptCollection
              where e.Id == dep.EmployeeId
              && dep.DepetarmentName =="a"
              select e)
             .ToList();

这是:

1
2
3
4
5
6
7
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();

更好的选择是:

1
2
3
4
5
6
var result = employeeCollection.Join(
            deptCollection.Where(dep => dep.DepetarmentName =="a"),
            e => e.Id,
            dep => dep.EmployeeId,
            (e,dep) => e)
       .ToList();

最接近查询语法(但我会说基于意见的看法不太好)是:

1
2
3
4
5
var result = employeeCollection.Join(
        deptCollection,
        e => new { e.Id,"a" },
        dep => new { dep.EmployeeId, dep.DepartmentName },
        (e,dep) => e).ToList();


Q1. What is the equivalent lamda statement for the above linq ?

1
2
3
4
5
var empindeptLamda = employeeCollection
    .Join(deptCollection, emp => emp.Id, dep => dep.EmployeeId, (e, dep) => new { e, dep })
    .Where(x => x.dep.DepetarmentName =="a")
    .Select(x => x.e)
    .ToList();

Q2. When should i choose LINQ vs Lamda method syntax or query syntax ?

这确实是您的个人喜好。 由于它们被编译为相同的IL,因此性能是相同的。 但是,在某些情况下,首选查询语法,例如具有多个join子句。 在其他时候,方法语法也很出色,例如添加您自己的扩展方法,或调试每个方法之间的中间结果。