Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq All & Any working differently on blank array

Tags:

c#

linq

Consider following linq example with blank array:

When Any() returns false as there is no number greater than zero how can All() return true conveying all numbers greater than zero ?

var arr = new int[] { }; Console.WriteLine(arr.Any(n => n > 0)); //false  Console.WriteLine(arr.All(n => n > 0)); //true  
like image 751
Prasan Kumar Avatar asked Aug 11 '16 14:08

Prasan Kumar


2 Answers

Seems logical to me.

  • All: Are all numbers in arr greater than zero (meaning there is no number not greater than zero) => true
  • Any: Is there any number in arr that is greater than zero => false

But more important, according to Boolean Algebra:

arr.All(n => n > 0);  

gives true, because it should be the logical opposite of

arr.Any(n => !(n > 0)); 

which gives false (actually this is what the above two points say).

like image 75
René Vogt Avatar answered Oct 14 '22 08:10

René Vogt


The implementation of All shows very clearly why.

    public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {         if (source == null) throw Error.ArgumentNull("source");         if (predicate == null) throw Error.ArgumentNull("predicate");         foreach (TSource element in source) {             if (!predicate(element)) return false;         }         return true;     } 

It runs a foreach over the collection. If there are no elements in the collection, it will skip the foreach and will return true.

Interestingly, the implementation on Any

    public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {         if (source == null) throw Error.ArgumentNull("source");         if (predicate == null) throw Error.ArgumentNull("predicate");         foreach (TSource element in source) {             if (predicate(element)) return true;         }         return false;     } 

This cleary shows they're opposites.

like image 32
Callum Linington Avatar answered Oct 14 '22 09:10

Callum Linington