这个问题在这里已有答案:
EF中的查询结果是实体列表
List<List<Entity>>
有没有办法将所有子列表连接到一个类型为List<Entity>
的列表中?
低效的方法是创建一个循环所有列表的方法,然后使用List的Concat方法。有没有办法更有效地做到这一点?
使用LINQ中的SelectMany
List<List<Entity>> yourList = GetYourList();
List<Entity> yourFlatList = yourList.SelectMany(l => l).ToList();
为了提高SelectMany
的性能(如果这是一个问题),考虑预先定义目标Capacity
的List
,并使用AddRange
。
代码可能类似于:
var listOfLists = new List<List<string>>();
// Setup test data
for (int i = 0; i < 10; i++)
{
listOfLists.Add(Enumerable.Range(0, 10000).Select(z => z.ToString()).ToList());
}
// Pre-allocate Capacity here - this will have the most benefit for listOfLists consisting of a small number of large lists
var capacity = 0;
for (int i = 0; i < listOfLists.Count; i++)
capacity += listOfLists[i].Count;
List<string> result = new List<string>(capacity);
for (int i = 0; i < listOfLists.Count; i++) // changed to for loop based on Tommaso's advice
{
result.AddRange(listOfLists[i]); // AddRange is faster than Add - https://stackoverflow.com/a/9836512/34092
}