Subscribe to our YouTube Channel for more Videos

Difference between Any() and Count() in LINQ


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

}
Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.