gpt4 book ai didi

c# - 如何使用 linq 和 lambda 表达式从两个单独的列表中创建字典

转载 作者:行者123 更新时间:2023-11-30 21:54:04 24 4
gpt4 key购买 nike

我正在练习 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 表达式是否可行?提前致谢

最佳答案

是的,你可以:

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

关于c# - 如何使用 linq 和 lambda 表达式从两个单独的列表中创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33488895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com