linq help for deep date list
I have a cla开发者_开发问答ss 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;
var tempDateList = Class2List.SelectMany(x => x.DateList()).ToList();
Forgot the ToList
since that is what you want.
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 theDateList
from the first class, all of theDateList
from the second class, etc)ToList()
creates a concreteList<DateTime>
from that data- the
var tempDateList
is fully static typed, and infersList<DateTime>
from the expression
精彩评论