If I have a class like this
public class Test
{
public string Id {get; set;}
public string Name {get; set;}
public int Value {get; set;}
}
and then:
List<Test> values = new List<Test>(); // this contains let's say 10 items
and I do like this:
var grouped = values.Where(x=>x.Value > 10).GroupBy(x=>x.Name);
My question is how can I check if grouped == null
? Or how can I check that there are no groupings that matches that criteria?
I am asking because if I do like this:
if (grouped == null) // this is false although the linq yielded no results
{
}
You can use method Any()
:
var anyItems = grouped.Any();
You do not need to check for null, because grouping would return an empty collection instead of null
You could check if there is no groups, like below:
var anyGroups = grouped.Any();
If there is at least one group, the extension method called Any
will return true
. Otherwise it will return false
.
According to MSDN, this is the signature of the method GroupBy
:
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
It is clear from the above that this method returns a sequence of items that implement the IGrouping
interface. (IGrouping
Represents a collection of objects that have a common key). An easy way to find out if a sequence contains elements, is using the enumerable's extension method called Any
.
Furthermore this is a O(1)
operation -using the Any
method and not passing any predicate in it. While using the enumerable's extension method called Count
, in some cases is an O(n)
operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With