C# Linq Query group by check if result is null

时间:2015-05-04 19:42:16

标签: c# linq

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
{

}

5 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:5)

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.

答案 2 :(得分:2)

GroupBy never returns null. When there are no records in the result, you would get an empty IEnumerable<IGrouping<TKey,TSource>> object.

In your case GroupBy is unnecessary: you can replace it with

var anyGreaterThanTen = values.Any(x=>x.Value > 10);

答案 3 :(得分:0)

Using Any() is good enough, but it not the most optimal solution.

You obviously need to iterate through the result after you have found that there are some results, but calling Any() before iterating over the result, causes the query to run two times. This is not a big deal for a simple example like you have here, but if it was a query over a database (LINQ to SQL or Entity Framework), then you had two database hits. Once to check that if there are any results, and next to fetch the results.

To avoid this, you can write:

bool hasResult = false;
// iterating over the result, and performing your task
foreach(var group in grouped)
{
    hasResult = true;

    // process data
    // ...
}

if(!hasResult)
{
    // ...
}

答案 4 :(得分:0)

检查结果是否为null时,我遇到同样的问题。所以,我调试了它。 我发现当结果没有组时,它有时没有元素或1个元素,但是这个元素是null。因此,要检查结果不为空的位置,我们应该结合以下两个条件:

if(grouped.Count() > 0 && grouped.ElementAt(0) != null)
    {
       //TODO:....enter code here
    }