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

}
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...