CodeBlanks Logo Icon CodeBlanks

Any and All

C# course · Intermediate · Lesson 94/116

Learn condition checks with Any and All.

Condition checks with Any and All

The Any method asks whether at least one element in the collection matches a condition. It returns true or false. numbers.Any(n => n > 100) checks if there is at least one large number.

The All method expects every element to match. numbers.All(n => n > 0) asks if all numbers are positive. Both return bool; they short-circuit and stop at the first matching or non-matching element.

Any versus All

Any is like a logical OR: one match is enough. All is like a logical AND: one non-match makes it false. On an empty collection, Any returns false and All returns true (a vacuous truth).

A parameterless Any() tells whether the collection is non-empty: list.Any() returns true when the list has elements. This is more efficient than list.Count > 0 because it does not count; it just checks for at least one.

Exercise Is there a negative?

Check whether the numbers array has at least one negative number using Any and print the result with Console.WriteLine.

Show example solution
Query with numbers.Any(n => n < 0), store the result, print with Console.WriteLine.
Example solution:
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 3, 7, -2, 8 };
        var has = numbers.Any(n => n < 0);
        Console.WriteLine(has);
    }
}

Test yourself

  1. When does Any return true?

    new[] { 1, 2, 3 }.Any(n => n > 2);
    • Never
    • When at least one element matches the condition
    • When all elements match
    • When the collection is empty
    Show answer

    Never — Correct. Any returns true when at least one element matches; in the example 3 > 2 so it returns true.

  2. Complete the Any call

    bool hasBig = numbers.____(n => n > 100);
    Show answer
    bool hasBig = numbers.Any(n => n > 100);
  3. Match each method to its behavior

    Any
    At least one matches
    All
    All match
    Any()
    Is non-empty
    All(n => n > 0)
    All positive

All lessons in Intermediate