C# LINQ MORETHEN(谓词,限制)扩展而不是Count(谓词)>;限制?

C# LINQ MORETHEN(谓词,限制)扩展而不是Count(谓词)>;限制?,c#,.net,linq,comparison,operator-keyword,C#,.net,Linq,Comparison,Operator Keyword,检查IEnumerable集合中满足谓词的元素是否多于或少于X的最佳方法是什么 我目前正在使用.Count(lambda)您可以使用以下表达式:.Skip(limit).Any()等效Count()>limit。但是如果您的列表是ICollection,Count()更可取 谓词版本: public static bool MoreThan<TSource>(this IEnumerable<TSource> source, Func<TSource, b

检查IEnumerable集合中满足谓词的元素是否多于或少于X的最佳方法是什么


我目前正在使用
.Count(lambda)您可以使用以下表达式:
.Skip(limit).Any()
等效
Count()>limit
。但是如果您的列表是
ICollection
Count()
更可取

谓词版本:

public static bool MoreThan<TSource>(this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate, int limit)
{
    int i = 0;

    foreach (var item in source)
    {
        if (predicate(item))
        {
            i++;

            if (i > limit)
            {
                return true;
            }
        }

    }

    return false;
}
公共静态bool MoreThan(此IEnumerable源代码,
Func谓词,int限制)
{
int i=0;
foreach(源中的var项)
{
if(谓语(项))
{
i++;
如果(i>限制)
{
返回true;
}
}
}
返回false;
}

您可以定义一些扩展方法:

static bool LessThan<T>(this IEnumerable<T> enumerable, int count, Func<T, bool> predicate)
{
    int found = 0;
    foreach (var item in enumerable)
    {
        if (predicate(item))
        {
            found++;
            if (found >= count)
                return false;
        }
    }
    return true;
}

static bool MoreThan<T>(this IEnumerable<T> enumerable, int count, Func<T, bool> predicate)
{
    int found = 0;
    foreach (var item in enumerable)
    {
        if (predicate(item))
        {
            found++;
            if (found > count)
                return true;
        }
    }
    return false;
}

这是如何回答这个问题的?它不会像问题所问的那样计算与谓词匹配的元素。@Kirill,SkipWhile(谓词)将在条件不再满足时返回所有元素。@Erwin,True。我从我的答案中删除了它。@Erwin,如果您使用
.Count(谓词)
,我认为这是最合适的解决方案。很好,尽管第一个应该是(find>Count),第二个应该是(find>=Count)。当匹配元素的数量等于您正在搜索的数量时,这将使它们返回true,这对“LessThan”和“MoreThan”这两个名字没有意义。
var col = new[] { 1, 6, 4, 8, 3, 5, 1, 7 };
var res1 = col.MoreThan(2, c => c == 1); //false
var res2 = col.MoreThan(1, c => c == 1); //true
var res3 = col.LessThan(4, c => c > 5); //true
var res4 = col.LessThan(3, c => c > 5); //false