Reputation: 15455
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;
Upvotes: 2
Views: 93
Reputation: 15242
var tempDateList = Class2List.SelectMany(x => x.DateList()).ToList();
Forgot the ToList
since that is what you want.
Upvotes: 4
Reputation: 1062945
Pretty simple really;
var tempDateList = Class2List.SelectMany(x => x.DateList).ToList();
SelectMany(x => x.DateList)
essentially performs like an inner loop here, creating a continuous sequence (all of the DateList
from the first class, all of the DateList
from the second class, etc)ToList()
creates a concrete List<DateTime>
from that datavar tempDateList
is fully static typed, and infers List<DateTime>
from the expressionUpvotes: 1