0

I have a collection A of let's say 100 items. From that list I want to perform a where clause which can rule out let's say 20 of items.

Is there a way to use Select clause or something else on items in which I could use external method that returns 2 items.

I would need to end up with 160 objects from the original list.

What I currently have is

public List<A> ToAList(B item)
{ 
   return new List<A> {new A(), new A()}; 
}

If I make this call

originalList.Where(x => true).Select(y => ToAList(y)).ToList();

I end up having a list of 80 (from pseudo example) two-item A lists instead of a list containing 160 objects A.

I am looking for a way to avoid loops. Just plain Select or AddRange trick that could result in one list.

Goran Sneperger
  • 77
  • 1
  • 1
  • 8
  • If `ToAList` does only that you could replace it with: `Enumerable.Range(0, originalList.Count * 2).Select(i => new A()).ToList();` – Tim Schmelter Sep 25 '18 at 13:12
  • It does a lot more but I wanted to have it written in such a way just to have a point. SelectMany does the trick as @Peter B wrote – Goran Sneperger Sep 25 '18 at 13:20

1 Answers1

2

You can use SelectMany:

originalList.Where(x => true).SelectMany(y => ToAList(y)).ToList();
Peter B
  • 22,460
  • 5
  • 32
  • 69