The Where method does not fulfill your request - it simply creates a request, which is then executed when the data is requested. This is called deferred execution. Therefore, in your first fragment, the filter is applied only when Count() is called, which was deleted after the red element was deleted.
In the second snippet, your call to ToList() causes the request to be executed immediately to create a new list. This is completely independent of the source list - therefore, removing an item from the source list does not affect the results.
It doesnβt depend on the type of q3 declaration - the important difference is just calling ToList() . Therefore, if you change the second fragment to:
var list = new List<string>(colors); IEnumerable<string> q3 = list.Where(c => c.Length == 3).ToList(); list.Remove("red"); listBox1.Items.Add("Oh! That is : " + q3.Count());
... you will see the same effect. The request will be executed before the item is deleted, after which the source list is not related to the contents of q3 .
For more information on LINQ extensions and outputs, you can read my Edulinq blog series .
Jon skeet
source share