I have a class with a list of a 2nd class which has a list of dates. What is the best way to get the entire list of dates in the top level class?
Given the following:
Class 1 contains:
Public List<Class2> Class2List;
Class 2 contains:
List<DateTime> DateList;
What is the best way to get the entire list of dates in Class 1? I know I can loop through each of the Class 2 items and then get the list that way, but I’m hoping there is a cleaner way with LINQ.
List<DateTime> tempDateList;
Foreach (var Class2 in Class2List)
{
Foreach (var dt in Class2.DateList)
{
tempDateList.Add(dt);
}
}
Return tempDateList;
Pretty simple really;
SelectMany(x => x.DateList)essentially performs like an inner loop here, creating a continuous sequence (all of theDateListfrom the first class, all of theDateListfrom the second class, etc)ToList()creates a concreteList<DateTime>from that datavar tempDateListis fully static typed, and infersList<DateTime>from the expression