日常生活的交流与学习

首页 新随笔 联系 管理

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.");
        }

    }
}
posted on 2024-09-13 19:00  lazycookie  阅读(9)  评论(0编辑  收藏  举报