Lambda在Join语句

时间:2016-08-02 12:34:29

标签: c# linq lambda

我必须根据Employee过滤department。我能用LINQ做同样的事情。

Linqlambda编译以获得相同的结果。编译器在编译之前将查询表达式更改为等效的Lambda expression,因此生成的IL完全相同。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();
  

我无法在此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子句

2 个答案:

答案 0 :(得分:4)

相当于此:

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

答案 1 :(得分:0)

  

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,因此性能是相同的。但是,存在一些首选查询语法的情况,例如具有多个join子句。和方法语法一样的其他时间,比如添加自己的扩展方法,或调试每个方法之间的中间结果。