有没有更好的方法来搜索列表与另一个列表

时间:2014-04-14 15:26:10

标签: c# linq

是否有更好的linq查询,以查看列表是否包含除以下内容之外的其他列表中的任何项目:

results.Where(r => r.Categories.Intersect(submittedCategories).Count() > 0)

其中r.categories是结果所在的类别列表,submittedCategories i是用户想要过滤的类别列表

4 个答案:

答案 0 :(得分:6)

我会使用Enumerable.Any代替Enumerable.Count

results.Where(r => r.Categories.Intersect(submittedCategories).Any())

方法Count()针对实现ICollection的源进行了优化(它只返回集合的Count属性值)。但Enumerable.Intersect的结果为IEnumerable<T>,因此在这种情况下,Count()会迭代所有集合:

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)    
        throw Error.ArgumentNull("source");

    ICollection<TSource> is2 = source as ICollection<TSource>;
    if (is2 != null)    
        return is2.Count;

    ICollection is3 = source as ICollection;
    if (is3 != null)    
        return is3.Count;

    int num = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext()) // you will fall into this case
           num++; 
    }
    return num;
}

这意味着应该从两个集合构建完整的交集,以了解结果中项目的总数。然后只有将值与零进行比较。

Any()将在找到第一个项目之后停止迭代,而不会找到所有相交的项目。

public static bool Any<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)    
        throw Error.ArgumentNull("source");

    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())        
            return true;        
    }
    return false;
}

另一个好处 - Any()可以更好地显示您的意图。

答案 1 :(得分:5)

  

是否有更好的linq查询,以查看列表中是否包含任何项目   另一个清单

如果您要查找任何匹配项,请使用Enumerable.Any代替Count()

results.Where(r => r.Categories.Intersect(submittedCategories).Any())

您可能会看到Any更适合Count()Which method performs better: .Any() vs .Count() > 0?

答案 2 :(得分:3)

您也可以在没有Any的情况下直接使用Intersect

results.Where(r => r.Categories.Any(submittedCategories.Contains))

答案 3 :(得分:1)

尝试使用Any()方法。

任何人都会收到谓词。它确定集合中的任何元素是否与特定条件匹配。

来源:Dotnetperls

相关问题