score:18

Accepted answer

updated (post c# 7) answer

if using c# 7 or 8 then one could use the is keyword together with linq.all:

var result = comparison.all(item => item.value is null)

if using c# 9 then one could use the is not null together with linq.any:

var result = comparison.any(item => item.value is not null)

if using c# 9 then one could also use the is object or is {} together with linq.any:

var result = comparison.any(item => item.value is object)

all these options are somewhat equivalent. at least in terms of time complexity they are all o(n). i guess the "preferred" option simply depends on personal opinion.


original (pre c# 7) answer

using linq method of all:

var result = comparison.all(item => item.value == null)

basically what it does is to iterate all items of a collection and check a predicate for each of them. if one does not match - result is false


score:1

i'm not totally sure about the internal differences of all and exists, but it might be a good idea to just check whether one of the entries is not null and then negate the result:

var result = !comparison.exists(o => o.value != null);

i would expect this query to quit after the first non-null value was found and therefore to be a little more efficient.

update: from the enumerable.all documentation:

the enumeration of source is stopped as soon as the result can be determined.

therefore, using all will probably not result in the entire list getting processed after a non-null value has been found.

so the aforementioned possible performance gain is not likely to occur and both solutions probably do not differ.

score:4

you can check by this linq statement

var isnull = comparison.all(item => item.value == null);

Related Query

More Query from same tag