Ever faced any of these questions?

My enumeration is empty!?

Where did my items go?

Why do Linq remove things I don’t want removed?

Where´s the items in my Where?!

I just did.

Linq is a nice little feature but when using enumerations you really need to keep your fingers crossed. Enumerations aren’t evaluated until you actually step through them so if you´re doing something like this:

// Select all items that fullfill a criteria, remove them and add them in the beginning of the list
var myItems = selection.Where(d => otherItems.Contains(d.Id));
selection.InsertRange(0, myItems);

You´re gonna get in trouble. Since we get an enumerable, this will be evaluated as a selected portion from the actual list, that is not an actual selection. So when getting to the RemoveAll we actually remove the items from Both selections, dough!

A simple yet crude way to solve this is to force the creation of a new selection using the ToList method to create a new list which will evaluate the entire enumeration and giving us a new collection:

var myItems = selection.Where(d => otherItems.Contains(d.Id)).ToList();