我有 2 个表,我想匹配 2 个 Id 值。
第一张 table
- 编号 - 1、2、3、4、5
- 部门编号 - 2、4、5、2、1
第二张表
- Id- 1, 2, 10, 30, 40
我想将第一个表的 ID 与第二个表的 ID 匹配,以便我可以获得 DepartmentId 值。
我需要得到这个虚拟结果:
- Id- 1, 2, 10, 30, 40
- DepartmentId -2, 4, null, null, null
这是我的代码:
for (int i = 0; i < model1.Count(); i++)
{
model1[i].DepartmentId= model2.FirstOrDefault(k => k.Id== model1[i].Id).DepartmentId;
}
我收到这个错误:
An exception of type 'System.NullReferenceException' occurred in IYP.UserInterfaceLayer.dll but was not handled in user code
我认为循环失败是因为它找不到 10、30、40 个 Id 值。如果我的 Id 值在 2 个表(Id = 1,2,3,4,5)中相同,则循环有效。
我如何使用 Linq 执行此操作?
最佳答案
您基本上是在 LINQ 中寻找 Left Join。试试这个:-
var query = from emp2 in Employee2
join emp1 in Employee1
on emp2.Id equals emp1.Id into allEmployees
from result in allEmployees.DefaultIfEmpty()
select new
{
ID = emp2.Id,
DeptID = result == null ? "No Department" : result.DepartmentId.ToString()
};
我使用以下类型的地方:-
var Employee1 = new[]
{
new { Id = 1, DepartmentId = 2 },
new { Id = 2, DepartmentId = 4 },
new { Id = 3, DepartmentId = 5 },
new { Id = 4, DepartmentId = 2 },
new { Id = 5, DepartmentId = 1 },
};
var Employee2 = new[]
{
new { Id = 1 },
new { Id = 2 },
new { Id = 10 },
new { Id = 30 },
new { Id = 40 },
};
完成工作 Fiddle .
关于c# - Linq 如何加入并获取 2 个表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26730067/