Join语句中的Lambda where条件

本文关键字:where 条件 Lambda 语句 Join | 更新日期: 2023-09-27 17:59:38

我必须根据department筛选Employee。我也可以用LINQ做同样的事情。

CCD_ 3和CCD_。编译器在编译查询表达式之前将其更改为等效的Lambda expression,因此生成的IL完全相同。源

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();

我无法在此lambda 中添加.Where子句

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子句

Join语句中的Lambda where条件

这方面的等价物:

var empinadept = (from e in employeeCollection
              from dep in deptCollection
              where e.Id == dep.EmployeeId
              && dep.DepetarmentName == "a"
              select e)
             .ToList();

这是吗

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();

更好的选择是:

var result = employeeCollection.Join(
            deptCollection.Where(dep => dep.DepetarmentName == "a"),
            e => e.Id,
            dep => dep.EmployeeId,
            (e,dep) => e)
       .ToList();

最接近查询语法的是:

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

Q1.对于上述linq,等效的lamda语句是什么?

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.我什么时候应该选择

LINQ vs Lamda方法语法或查询语法?

这确实是你个人的喜好。由于它们被编译成相同的IL,因此性能是相同的。然而,在某些情况下,查询语法是首选的,例如具有多个联接子句。其他时候,方法语法会大放异彩,比如添加自己的扩展方法,或者调试每个方法之间的中间结果。