Search code examples
c#listienumerabledeferredaddrange

List.AddRange with IEnumerable<T> parameter not working?


I have the following scenario where I want to add some items to a List...

List<T> items = new List<T>();
IEnumerable<T> addItems = someCollection.Where(...);
items.AddRange(addItems);

Using this code, no items are added to the list but if I add a .ToList() after then Linq statement then the items are added correctly. I guess this is due to deferred execution but I would have thought that given the List.AddRange function accepts an IEnumerable that it would enumerate the items to be added.

Can someone please clear up why this happens?


Solution

  • Thanks for the replies. I tried to simplify the code for this example but as usual, the devil's in the details!

    Between the .Where() statement and the AddRange() call the code was (deep down) clearing the source ('items' in this example) list. The developer didn't realise that the filter was deferred until the AddRange() call at which point they had already cleared the source list.

    Glad to know I haven't lost the plot :)