'Check null value in a list using linq
I have a list List<OfferComparison> Comparison
. I want to
check if all the items have Value == null
in an if
condition.
How can I do it with linq?
public class OfferComparison : BaseModel
{
public string Name { get; set; }
public string Value { get; set; }
public bool Valid { get; set; }
}
Solution 1:[1]
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
Solution 2:[2]
You can check by this linq statement
var isNull = Comparison.All(item => item.Value == null);
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Mostafiz |
Solution 3 |