Search code examples
c#linqienumerableaddrange

Why does adding a list to another list, using add range, remove the elements from the first list?


Consider the following example:

IEnumerable<Int32> groupsToAdd = new List<Int32>();

List<Int32> groups1 = new List<Int32>() { 1,2,3 };
List<Int32> groups2 = new List<Int32>() { 3,4,5 };

groupsToAdd = groups1.Where(g => false == groups2.Contains(g));

groups2.AddRange(groupsToAdd);

groupsToAdd.Dump();

When groupsToAdd.Dump() is called the list is now empty. I've looked up the AddRange reference and it doesn't mention that the elements are removed from list but when i test this code (in linqpad) it ends empty. Why is this?

Edit: To clarify, I mean that the elements are being removed from groupsToAdd because before groups2.AddRange(groupsToAdd) groupsToAdd is populated with two elements


Solution

  • It's because of the IEnumerable. When you set groupsToAdd to the result of groups1.Where(g => false == groups2.Contains(g)) there is deferred execution, which means that the query is not run until AddRange() and then again at Dump(). Because the list, groups2, now contains the elements they no longer are a result of the original query.