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

}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...