Most of the developers would have come across Any() and Count() when using LINQ in C# . What is difference between Any() and Count() in LINQ ?
Difference between Any() and Count() in LINQ
Assume , you want to know if the collection contains records based on some criteria and you have the option of using Count() and Any()
When using Count() keyword in LINQ query or collection , it will traverse the complete list to calculate the number of records which might sometimes be inefficient.
The Any() LINQ extension method on the otherhand will stop as soon as the result is found.
Below is a sample sourcecode demonstrating the usage of Any() and Count() in LINQ
Data
public class BlockbusterMovie { public string Name { get; set; } } public class BlockbusterMovies : List<BlockbusterMovie> { public BlockbusterMovies() { Add(new BlockbusterMovie { Name = "Vishwaroopam" }); Add(new BlockbusterMovie { Name = "Endhiran" }); Add(new BlockbusterMovie { Name = "Thuppaki" }); Add(new BlockbusterMovie { Name = "Mankatha" }); } }
Example of Any() in LINQ
List<BlockbusterMovie> movies = new BlockbusterMovies(); bool Found1 = movies.Any(a => a.Name == "Vishwaroopam"); if (Found1) { //Logic }
Example of Count() in LINQ
bool Found2 = movies.Count(a => a.Name == "Vishwaroopam") > 0; if (Found2) { //Logic }