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

时间:2015-11-02 23:28:29

标签: c# linq

我正在练习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表达式? 在此先感谢

2 个答案:

答案 0 :(得分:3)

是的,你可以:

    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());

答案 1 :(得分:0)

有可能。

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

将上一段翻译成LINQ给我们

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

我想在这里指出的是,LINQ可以很容易地被翻译成简单的英语并被任何人理解。从英语到LINQ的翻译通常也是可能的 - 您只需使用LINQ中提供的单词(方法)来重新解释您的问题。