使用LINQ Enumerable All避免冗余

时间:2013-07-17 06:30:32

标签: c# linq ienumerable redundancy

IEnumerable<T>.All是布尔数组时,我常常觉得T方法是多余的。

鉴于以下示例代码,是否有更好的方法来验证使用All方法

bool isOrdered = firstList
     .Zip(secondList, (first,second)=>first==second)
     .All(areSame => areSame); /* feels redundant */

在其他一些语言中,只需调用.All()即可确保所有元素都为真。在没有akward .All(x=>x)

的情况下,c#中的这种情况是可能的

1 个答案:

答案 0 :(得分:3)

您无法避免All运算符中的谓词。它是签名的一部分,它不是可选的:

public static bool All<TSource>(this IEnumerable<TSource> source, 
                                Func<TSource, bool> predicate)

您可以创建自己的All(或更好的AllTrue)扩展程序,专门用于收集布尔值:

public static bool AllTrue(this IEnumerable<bool> source)
{
    return source.All(b => b);
}

public static bool AllFalse(this IEnumerable<bool> source)
{
    return source.All(b => !b);
}

用法:

bool isOrdered = firstList
     .Zip(secondList, (first,second) => first == second)
     .AllTrue();
相关问题