Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

foreach

linq

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));
}
like image 625
Usman Khan Avatar asked Oct 12 '18 10:10

Usman Khan


Video Answer


1 Answers

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)));
like image 54
fubo Avatar answered Oct 06 '22 01:10

fubo