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
:
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(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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With