What is the difference between All and Any in C# Linq?

CsharpServer Side ProgrammingProgramming

Any(<predicate>) method returns true if at least one of the elements in the source sequence matches the provided predicate. Otherwise, it returns false. On the other hand, the All(<predicate>) method returns true if every element in the source sequence matches the provided predicate. Otherwise, it returns false

Example

static void Main(string[] args){
   IEnumerable<double> doubles = new List<double> { 1.2, 1.7, 2.5, 2.4 };
   bool result = doubles.Any(val => val < 1);
   System.Console.WriteLine(result);
   IEnumerable<double> doubles1 = new List<double> { 0.8, 1.7, 2.5, 2.4 };
   bool result1 = doubles1.Any(val => val < 1);
   System.Console.WriteLine(result1);
   Console.ReadLine();
}

Output

False
True

Example

static void Main(string[] args){
   IEnumerable<double> doubles = new List<double> { 0.8, 0.9, 0.6, 0.7 };
   bool result = doubles.All(val => val < 1);
   System.Console.WriteLine(result);
   IEnumerable<double> doubles1 = new List<double> { 0.8, 0.9, 1.0, 0.7 };
   bool result1 = doubles1.All(val => val < 1);
   System.Console.WriteLine(result1);
   Console.ReadLine();
}

Output

True
False
raja
Published on 05-Dec-2020 11:00:39
Advertisements