HomeCSharpDifference between Any() and Count() in LINQ

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...