简体   繁体   English

我可以使用LINQ从现有列表创建新的对象列表

[英]Can I use LINQ to create a new list of objects from an existing list

I have a list of invoices that have both start and end dates. 我有一份包含开始和结束日期的发票清单。 Can I use LINQ to get all the start and end dates from the invoice list and put them into a new list of type Period : 我可以使用LINQ从发票清单中获取所有开始日期和结束日期,并将它们放入类型为Period的新列表中:

Period(DateTime startDate, DateTime endDate) {};

I can do this with a foreach as shown below but wanted to know if there was a better way to do this with LINQ. 我可以使用foreach执行此操作,如下所示,但想知道是否有更好的方法来使用LINQ。

foreach(Invoice invoice in invoices)
{
    periods.Add(new Period(invoice.StartDate, invoice.EndDate));
}

If you want to create a new periods list: 如果要创建新的期间列表:

List<Period> periods = invoices.Select(i => new Period(i.StartDate, i.EndDate)).ToList();

If you want to attach the invoice items to a existing periods list: 如果要将发票项目附加到现有期间列表:

periods.AddRange(invoices.Select(i => new Period(i.StartDate, i.EndDate)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM