Prasan Kumar Prasan Kumar - 1 year ago 83
C# Question

C# Linq All & Any working differently on blank array

Consider following linq example with blank array:


as there is no number greater than zero how can
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

Answer Source

Seems logical to me.

  • All: Are all numbers in arr are 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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download