如何仅使用一个未链接的LINQ指令来连接两个或多个集合? [重复]

问题描述 投票:-2回答:2

这个问题在这里已有答案:

EF中的查询结果是实体列表

List<List<Entity>>

有没有办法将所有子列表连接到一个类型为List<Entity>的列表中?

低效的方法是创建一个循环所有列表的方法,然后使用List的Concat方法。有没有办法更有效地做到这一点?

c# entity-framework linq
2个回答
2
投票

使用LINQ中的SelectMany

List<List<Entity>> yourList = GetYourList();
List<Entity> yourFlatList = yourList.SelectMany(l => l).ToList();

1
投票

为了提高SelectMany的性能(如果这是一个问题),考虑预先定义目标CapacityList,并使用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
}
© www.soinside.com 2019 - 2024. All rights reserved.