LINQ Any Operator

C#  LINQ  C#  linq 

LINQ Any operator comes under Quantifier Operators category in LINQ Query operators. LINQ Any operator is used for two cases:

  1. Check whether sequence is blank or not.
  2. Check whether any single element in a sequence satisfy a given condition or not.

Any operator is only available in Method syntax and not available in Query Syntax.

Below is the syntax of Any operator

public static bool Any<TSource>(this IEnumerable<TSource> source);
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

First overload takes zero parameters and it is used to check whether sequence contains any element or not.

Second overload takes predicate function as parameter and apply that condition to check whether any element in a sequence satisfy this condition or not.

C# LINQ Any Example for First Case

In first case, we have a list of students and we have to check that is this sequence has any item or not?

List<Student> students = new List<Student>();
if(students.Any())
{
    Console.WriteLine("List has one or more items");
}
else
{
    Console.WriteLine("List has no items");
}

Try It

List has no items

C# LINQ Any Example for Second Case

In this case, we have a list of students and we have to check whether any student is minor or not. For this, we have to check that is there any student in students collection whose age is smaller than 18 years? We have to only confirm whether minor students have or not and do not need particular minor students names.

Below is the code example:

List<Student> students = new List<Student>();
students.Add(new Student { ID = 1, Name = "Kapil", Age = 22 });
students.Add(new Student { ID = 2, Name = "Ramesh", Age = 17 });
students.Add(new Student { ID = 3, Name = "Raj", Age = 24 });
students.Add(new Student { ID = 4, Name = "Anil", Age = 25 });

if (students.Any(w => w.Age < 18))
{
    Console.WriteLine("There are minor students in list.");
}
else
{
    Console.WriteLine("No minor students");
}

Try It

There are minor students in list.

Join our newsletter and get an occasional email with a technology and DotNetPattern.com news update.