Essential C# LINQ Queries  Suggest an edit

Any

Any is used to check if any element of a collection matches a condition or not. see also: .All, Any and FirstOrDefault: best practice

1. Empty parameter

Any: Returns true if the collection has any elements and false if the collection is empty:

var numbers = new List<int>();
bool result = numbers.Any(); // false

var numbers = new List<int>(){ 1, 2, 3, 4, 5};
bool result = numbers.Any(); //true

2. Lambda expression as parameter

Any: Returns true if the collection has one or more elements that meet the condition in the lambda expression:

var arrayOfStrings = new string[] { "a", "b", "c" };
arrayOfStrings.Any(item => item == "a");    // true
arrayOfStrings.Any(item => item == "d");    // false

3. Empty collection

Any: Returns false if the collection is empty and a lambda expression is supplied:

var numbers = new List<int>();
bool result = numbers.Any(i => i >= 0); // false

Note: Any will stop iteration of the collection as soon as it finds an element matching the condition. This means that the collection will not necessarily be fully enumerated; it will only be enumerated far enough to find the first item matching the condition.

Live Demo on .NET Fiddle


Table Of Contents
22 Enum
25 GUID
65 LINQ Queries
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close