本文介绍了Linq所有空集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查所有定义是否都包含某些特定数据.除GroupBy返回空集合的情况外,此方法都可以正常工作.

I need to check if all definitions contains some specific data. It works fine except the case when GroupBy returns empty collection.

var exist = dbContext.Definitions
                     .Where(x => propertyTypeIds.Contains(x.PropertyTypeId) && x.CountryId == countryId)
                     .GroupBy(x => x.PropertyTypeId)
                     .All(...some condition...);

如何重写此代码,以便在空集合中所有人都将返回false?

How to rewrite this so All would return false on empty collection?

更新:这是SQL的LINQ,我想在一次调用中执行.

UPDATE:It is a LINQ to SQL and I wanted to execute this in single call.

UPDATE2:我认为这可行:

UPDATE2:I think this works:

var exist = dbContext.Definitions
                     .Where(x => propertyTypeIds.Contains(x.PropertyTypeId) && x.CountryId == countryId)
                     .GroupBy(x => x.PropertyTypeId)
                     .Count(x => x
                        .All(...some condition...)) == propertyTypeIds.Count;

推荐答案

如果您使用的是LINQ to Objects,我会编写自己的扩展方法.我的 Edulinq项目具有 All ,并进行调整非常简单:

If you're using LINQ to Objects, I'd just write my own extension method. My Edulinq project has sample code for All, and adapting that is pretty simple:

public static bool AnyAndAll<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }
    if (predicate == null)
    {
        throw new ArgumentNullException(nameof(predicate));
    }

    bool any = false;
    foreach (TSource item in source)
    {
        any = true;
        if (!predicate(item))
        {
            return false;
        }
    }
    return any;
}

这避免了多次评估输入.

This avoids evaluating the input more than once.

这篇关于Linq所有空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 18:51