Back
Close

Using C# LINQ - A Practical Overview

player_one
1637.7K views

Any(<predicate>) method

Returns true if at least one of the elements in the source sequence matches the provided predicate. Otherwise it returns false.

IEnumerable<double> doubles = new List<double> { 1.2, 1.7, 2.5, 2.4 };
// Will return false
bool result = doubles.Any(val => val < 1);

NOTE: Any() can also be called without a predicate, in which case it will return true if there is at least one element in the source sequence.

All(<predicate>) method

Returns true if every element in the source sequence matches the provided predicate. Otherwise it returns false.

IEnumerable<string> strings = new List<string> { "one", "three", "five" };
// Will return true
bool result = strings.All(str => str.Contains("e"));

Any() / All() quiz

string result = "none";
IEnumerable<string> strings = new List<string> { "four", "one", "two", "three", "five" };
if (strings.Take(3).Any(s => s.StartsWith("a")))
{
    if (strings.Skip(1).Take(2).All(s => s.Length == 3))
    {
        result = "red";
    }
    else
    {
        result = "orange";
    }
}
else
{
    if (strings.All(s => s.Length > 2))
    {
        if (strings.OrderBy(s => s).Take(3).Any(s => s == "one"))
        {
            result = "yellow";
        }
        else
        {
            result = "green";
        }
    }
    else
    {
        result = "blue";
    }
}
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io