Why does adding a list to another list using the add range remove items 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 looked at the AddRange link and does not mention that the elements are removed from the list, but when I test this code (in linqpad) it ends up empty. Why is this?

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

+4
source share
2 answers

This is due to IEnumerable. When you set groupToAdd to the result of groups1.Where(g => false == groups2.Contains(g)) , delayed execution is performed, which means that the request does not start until AddRange () and then again in Dump (). Since the list, groups2, now contains items, they are no longer the result of the original query.

+7
source

What is important to remember when using LINQ is that it leads to a query, not the results of that query. groupsToAdd not a list of elements, it is just a query definition that some elements can receive when necessary.

groupsToAdd does not actually iterate the original sequence (which is groups1 ) or does predicate checking (which depends on the state of groups2 ) until it repeats.

You repeat groupsToAdd twice. Once with AddRange call and again with Dump call. The second time you repeat it, group2 has changed, and therefore the query results have also changed.

If you want to avoid this delayed execution, you can materialize the request immediately by changing the code this way:

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

This will evaluate the query at that point in time so that groupsToAdd present the query results instead of the query itself.

+10
source

Source: https://habr.com/ru/post/1498073/


All Articles