Search code examples
listlinqaddrange

Using linq to append list to list from select method


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.


Solution

  • You can use SelectMany:

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