如何使用linq和lambda表达式从两个单独的列表中创建Dictionary

本文关键字:单独 两个 列表 Dictionary 创建 linq 何使用 lambda 表达式 | 更新日期: 2023-09-27 18:20:21

我正在练习Linq和Lambda表达式。我有两个这样的课程:

public class Invoice
{
    public int InvoiceId { get; set; }
    public int EmployeeId { get; set; }
    public DateTime InvoiceDate { get; set; }
    public DateTime DueDate { get; set; }
    public bool? IsPaid { get; set; }
    public Invoice()
    {
    }
    public Invoice(int invoiceId, int employeeId, DateTime invoiceDate, DateTime dueDate, bool? isPaid)
    {
        InvoiceId = invoiceId;
        EmployeeId = employeeId;
        InvoiceDate = invoiceDate;
        DueDate = dueDate;
        IsPaid = isPaid;
    }
}

和:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public DateTime BirthDate { get; set; }
    public string Department { get; set; }
    public double Rating { get; set; }
    public int EmployeeType { get; set; }
    public Person(string firstName, string lastName, int id, DateTime birthDate, string department, double rating, int employeeType)
    {
        FirstName = firstName;
        LastName = lastName;
        ID = id;
        BirthDate = birthDate;
        Department = department;
        Rating = rating;
        EmployeeType = employeeType;
    }
    public Person()
    {
    }
}

我有两个清单:

List<Person> employee = new List<Person> {//some instances of Person here}

List<Invoice> invoices = new List<Invoice> {//some instances of invoice here}

如您所见,Invoice类中的EmployeeId指的是Person的ID。我想创建一个像这样的字典:

var myDictionary=new Dictionary<"employeeName", List<employeeInvoices> >

对于linq和lambda表达式,这可能吗?提前感谢

如何使用linq和lambda表达式从两个单独的列表中创建Dictionary

可以:

    Dictionary<string, List<Invoice>> result = employee.ToDictionary(e => string.Format("{0} {1}", e.FirstName, e.LastName),
        e => invoices.Where(i => i.EmployeeId == e.ID).ToList());

这是完整的代码:

        var employee = new List<Person>() {
            new Person("FN", "LN", 1, new DateTime(1900, 1, 1), "", 1.1, 1),
            new Person("FN1", "LN1", 2, new DateTime(1900, 1, 1), "", 1.1, 1)
        };
        var invoices = new List<Invoice>() {
            new Invoice(1, 1, DateTime.Now, DateTime.Now, false),
            new Invoice(2, 2, DateTime.Now, DateTime.Now, false),
            new Invoice(3, 1, DateTime.Now, DateTime.Now, false),
        };
        Dictionary<string, List<Invoice>> result =
            employee.ToDictionary(e => string.Format("{0} {1}", e.FirstName, e.LastName),
                e => invoices.Where(i => i.EmployeeId == e.ID).ToList());

这是可能的。

您希望将员工列表转换为字典,其中关键字为员工,值为EmployeeId等于员工的ID的发票列表。

将上面的段落翻译成LINQ给了我们

var myDictionary = employees.ToDictionary(
                        emp => emp, 
                        emp => invoices.Where(inv => inv.EmployeeId == emp.ID).ToList());

我想指出的是,LINQ可以很容易地翻译成通俗易懂的英语,任何人都能理解。从英语翻译成LINQ通常也是可能的——你只需要使用LINQ中可用的单词(方法)来重新表述你的问题。