LINQ / C#

LINQ Any Operator

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

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

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

Below is the syntax of Any operator

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

The first overload takes zero parameters and is used to check whether a sequence contains any element or not.

The second overload takes a predicate function as a parameter and applies that condition to check whether any element in a sequence satisfies this condition or not.

C# LINQ Any Example for First Case

In the first case, we have a list of students, and we have to check if this sequence has any items 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");
}

Result
------
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 a minor or not. For this, we have to check if there are any students in the student collection whose age is less than 18 years. We have to only confirm whether minor students have names 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");
}

Result
------
There are minor students in list.