我正在练习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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句