Why do List.Count () and IEnumerable.Count () return different results?

We have this array in LINQ.

string[] colors = { "green", "brown", "blue", "red" }; 

and this code returns 0.

 var list = new List<string>(colors); IEnumerable<string> q3 = list.Where(c => c.Length == 3); list.Remove("red"); listBox1.Items.Add("Oh! That is : " + q3.Count()); 

and other return 1.

 var list = new List<string>(colors); List<string> q3 = list.Where(c => c.Length == 3).ToList(); list.Remove("red"); listBox1.Items.Add("Oh! That is : " + q3.Count()); 

Why is this happening? What is the difference between list and Ienumerable?

+7
list c # linq ienumerable
source share
2 answers

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 .

+19
source share

IEnumerable is an interface, and a list is a class.

And IEnumerable can only store values, but you cannot edit them, like adding or removing values.

Also, when you execute .ToList() , the query is executed in the database if you select items from db.

0
source share

All Articles