gpt4 book ai didi

c# - Join 语句中的 Lambda where 条件

转载 作者:行者123 更新时间:2023-12-02 08:37:35 26 4
gpt4 key购买 nike

我必须过滤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();

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。上述 linq 的等效 lambda 语句是什么?(如何在方法语法中添加 linq 中的 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();

关于c# - Join 语句中的 Lambda where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38720575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com