LINQ中的Join
在LINQ中,Join
操作符用于连接两个序列中的元素,基于给定的键匹配。Join
操作符允许你根据共同的键来关联两个序列中的项,这对于处理多个相关联的数据集非常有用。
代码
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
var employees = new List<Employee>
{
new Employee { Id = 1, Name = "Alice" },
new Employee { Id = 2, Name = "Bob" },
new Employee { Id = 3, Name = "Charlie" },
new Employee { Id = 1, Name = "Dena" }
};
var departments = new List<Department>
{
new Department { Id = 1, Name = "HR" },
new Department { Id = 2, Name = "IT" },
new Department { Id = 3, Name = "Finance" }
};
// IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector);
var employeeDepartments = employees.Join(
departments,
e => e.Id,
d => d.Id,
(e, d) => new { Employee = e.Name, Department = d.Name }
);
foreach (var item in employeeDepartments)
{
Console.WriteLine($"{item.Employee} works in the {item.Department} department.");
}
}
}
标签:join,Name,linq,public,Department,Employee,new,Id
From: https://www.cnblogs.com/zhuoss/p/18410263