In most code that you find that uses lists you will find something like this:
if(products.Count() > 0) { // Do stuff }
Personally, I’ve seen this literally thousands of times. While this works and gets the job done, there is one issue with this method. It enumerates the entire enumerable collection. What if you have 10,000 items in your collection? What if that collection has a bunch of other nested LINQ queries that must be executed prior to the actual count can be evaluated?
A simpler way to identify if the sequence contains any elements is to use the .Any() method. From the .Any() MSDN article:
“Determines whether a sequence contains any elements.”
Later in the article it states:
“The enumeration of source (the source enumeration) is stopped as soon as the result can be determined.”
In English .. the Any() method stops enumerating the enumeration as soon as it finds the first element. This is the same for the overload of the function as well.
Therefore you could do this:
var products = productService().GetProducts(); if(products.Any()) { // Do Stuff }
… and you would get the same effect as Count() without the overhead of processing the entire enumeration.
Sdjf says
Not always true. See this SO comment for more information:
http://stackoverflow.com/questions/305092/which…
Best Hosting says
I get it crystal clear idea about this topic.All information are described very clearly.