0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ Any in C#: Syntax and Examples

Use Any() in LINQ to check if a collection contains any elements or if any elements satisfy a condition. It returns true if at least one element matches; otherwise, false. You can call Any() without parameters to check for any elements or with a predicate to check a condition.
📐

Syntax

The Any() method has two common forms:

  • collection.Any(): Returns true if the collection has at least one element.
  • collection.Any(predicate): Returns true if any element in the collection satisfies the predicate condition.

The predicate is a function that takes an element and returns true or false.

csharp
bool Any();
bool Any(Func<T, bool> predicate);
💻

Example

This example shows how to use Any() to check if a list has any elements and if any element is greater than 10.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 8, 12, 3 };

        bool hasAny = numbers.Any();
        Console.WriteLine($"List has any elements: {hasAny}");

        bool hasGreaterThan10 = numbers.Any(n => n > 10);
        Console.WriteLine($"Any number greater than 10: {hasGreaterThan10}");

        bool hasGreaterThan20 = numbers.Any(n => n > 20);
        Console.WriteLine($"Any number greater than 20: {hasGreaterThan20}");
    }
}
Output
List has any elements: True Any number greater than 10: True Any number greater than 20: False
⚠️

Common Pitfalls

Common mistakes when using Any() include:

  • Using Any() on a null collection, which causes a NullReferenceException. Always ensure the collection is not null before calling Any().
  • Confusing Any() with All(). Any() checks if at least one element matches, while All() checks if all elements match.
  • Using Any() without a predicate when you want to check a condition, which will only check if the collection has elements.
csharp
List<int> numbers = null;

// Wrong: causes exception
// bool result = numbers.Any();

// Right: check for null first
bool result = numbers != null && numbers.Any();
📊

Quick Reference

Remember these tips when using Any():

  • Use without parameters to check if collection is not empty.
  • Use with a predicate to check if any element meets a condition.
  • Check for null before calling Any() to avoid exceptions.
  • Returns a boolean: true if condition met, otherwise false.

Key Takeaways

Use Any() to quickly check if a collection has elements or if any element meets a condition.
Always check for null before calling Any() to avoid exceptions.
Any() returns true as soon as it finds a matching element, making it efficient.
Use a predicate inside Any() to test specific conditions on elements.
Do not confuse Any() with All(); they serve different purposes.