简体   繁体   English

C#Linq查询组,检查结果是否为null

[英]C# Linq Query group by check if result is null

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 ? 我的问题是如何检查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() : 您可以使用方法Any()

var anyItems = grouped.Any();

You do not need to check for null, because grouping would return an empty collection instead of null 您不需要检查null,因为分组将返回空集合而不是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 . 如果至少有一个组,则名为Any的扩展方法将返回true Otherwise it will return false . 否则它将返回false

According to MSDN , this is the signature of the method GroupBy : 根据MSDN ,这是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接口的一系列项。 ( IGrouping Represents a collection of objects that have a common key). IGrouping表示具有公共密钥的对象的集合)。 An easy way to find out if a sequence contains elements, is using the enumerable's extension method called Any . 查找序列是否包含元素的简单方法是使用名为Any的枚举扩展方法。

Furthermore this is a O(1) operation -using the Any method and not passing any predicate in it. 此外,这是一个O(1)操作 - 使用Any方法而不传递任何谓词。 While using the enumerable's extension method called Count , in some cases is an O(n) operation. 使用名为Count的枚举扩展方法时,在某些情况下是O(n)操作。

GroupBy never returns null . GroupBy永远不会返回null When there are no records in the result, you would get an empty IEnumerable<IGrouping<TKey,TSource>> object. 当结果中没有记录时,您将获得一个空的IEnumerable<IGrouping<TKey,TSource>>对象。

In your case GroupBy is unnecessary: you can replace it with 在您的情况下, GroupBy是不必要的:您可以用它替换它

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

Using Any() is good enough, but it not the most optimal solution. 使用Any()就足够了,但它不是最优的解决方案。

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. 您显然需要在找到结果后迭代结果,但在迭代结果之前调用Any()会导致查询运行两次。 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. 对于像这里一样的简单示例,这不是什么大问题,但如果它是对数据库(LINQ to SQL或Entity Framework)的查询,那么您有两个数据库命中。 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)
{
    // ...
}

I have the same problem when checking whether result is null. 检查结果是否为null时,我遇到同样的问题。 So, I've debugged it. 所以,我调试了它。 I've found that when a result has no group, it sometimes has no element or 1 element but this element is null. 我发现当结果没有组时,它有时没有元素或1个元素,但是这个元素是null。 Therefore, to check where the result is not null, we should combine 2 conditions like below: 因此,要检查结果不为null的位置,我们应该结合以下两个条件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM