-2

The result of a query in EF is a List of List of an entity

List<List<Entity>>

Is there a way to concat all child List's into only one List of type List<Entity>?

The inefficient way is to create a method that loops for all lists and then use Concat method of the List. Is there a way to do that more efficiently?

jstuardo
  • 3,901
  • 14
  • 61
  • 136

2 Answers2

2

Using SelectMany from LINQ

List<List<Entity>> yourList = GetYourList();
List<Entity> yourFlatList = yourList.SelectMany(l => l).ToList();
NetMage
  • 26,163
  • 3
  • 34
  • 55
Dave
  • 2,829
  • 3
  • 17
  • 44
1

To improve performance over SelectMany (if that is a concern), consider pre-defining the Capacity of the target List, and also using AddRange.

The code may look something like:

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
}
mjwills
  • 23,389
  • 6
  • 40
  • 63
  • I added your code in the following link http://rextester.com/HBVHM39216, and the performance is so and so... of course, if your exclude your capacity calculation from the stopwatch timing it's good (but still not as good as a for loop), but that's what I call cheating xD – Tommaso Belluzzo Dec 27 '17 at 00:48
  • Great feedback, thanks @TommasoBelluzzo . For small sets of data (like in your benchmark) then the choice of looping structure will make a larger impact - as your benchmark shows. As the size of the list grows then AddRange will make a bigger impact, as shown at http://rextester.com/YDE87506 . In terms of the benefits of pre-allocating `Capacity`, rextester doesn't show that that well - you'd need to confirm on your local PC. But on my machine running 4.6.1 in Release mode there is a slight edge (since the cost of calculating the capacity is less than the cost of the memory allocations). – mjwills Dec 27 '17 at 01:10
  • For the downvoter, I'd love to learn more about how to improve the answer. Feel free to leave feedback! _StackOverflow is a great website to refine your skills, and I am certainly not offended to hear there is a better way._ – mjwills Dec 27 '17 at 02:48