列出列表列表

时间:2015-08-06 00:33:21

标签: c# linq

我有List<List<CustomType>>。每个List<CustomType>仅包含1个CustomType。如何将List<List<CustomType>>设为List<CustomType>

1 个答案:

答案 0 :(得分:3)

如上所述,您可以使用SelectMany()。鉴于这样的事情:

List<List<CustomType>> listOfLists = Init() ;

你可以简单地说:

List<CustomType> flattenedList = listOfLists.SelectMany().ToList() ;

但是,既然您知道每个嵌套列表都包含一个项目,您可以简单地说出以下任何一个:

  • List<CustomType> flattenedList = listOfLists.Select( x => x.First() ).ToList() ;

  • List<CustomType> flattenedList = listOfLists.Select( x => x[0] ) ;