What is the difference between Contains and Any in LINQ?

前端 未结 5 1553
孤独总比滥情好
孤独总比滥情好 2020-11-30 08:49

What is the difference between Contains and Any in LINQ?

5条回答
  •  野性不改
    2020-11-30 09:07

    Contains cares about whether the source collection is an ICollection, Any does not.

    Enumerable.Contains http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#f60bab4c5e27a849

    public static bool Contains(this IEnumerable source, TSource value)
    {
        ICollection collection = source as ICollection;
        if (collection != null)
        {
            return collection.Contains(value);
        }
        return source.Contains(value, null);
    }
    

    Enumerable.Any http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#6a1af7c3d17845e3

    public static bool Any(this IEnumerable source, Func predicate)
    {
        foreach (TSource local in source)
        {
            if (predicate(local))
            {
                return true;
            }
        }
        return false;
    }
    

提交回复
热议问题