开发者

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 the DateList from the first class, all of the DateList from the second class, etc)
  • ToList() creates a concrete List<DateTime> from that data
  • the var tempDateList is fully static typed, and infers List<DateTime> from the expression
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜