What is the difference between Contains and Any in LINQ?

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

What is the difference between Contains and Any in LINQ?

相关标签:
5条回答
  • 2020-11-30 08:56

    Contains takes an object, Any takes a predicate.

    You use Contains like this:

    listOFInts.Contains(1);
    

    and Any like this:

    listOfInts.Any(i => i == 1);
    listOfInts.Any(i => i % 2 == 0); // Check if any element is an Even Number
    

    So if you want to check for a specific condition, use Any. If you want to check for the existence of an element, use Contains.

    MSDN for Contains, Any

    0 讨论(0)
  • 2020-11-30 08:57

    Contains

    Determines whether a sequence contains a specified element by using the default equality comparer.

    Any

    Determines whether a sequence contains any elements.

    As for the documentation:

    Can't seem to find to find any documentation on it.

    All (most?) LINQ extension methods: here

    0 讨论(0)
  • 2020-11-30 08:59

    Contains checks if the sequence contains a specified element.

    Enumerable.Any checks if element of a sequence satisfies a condition.

    Consider the following example:

    List<int> list = new List<int> { 1, 2, 3, 4, 5 };
    bool contains = list.Contains(1); //true
    
    bool condition = list.Any(r => r > 2 && r < 5);
    
    0 讨论(0)
  • 2020-11-30 09:04

    Another difference as mentioned here is on the performance

    • Contains is O(n) for a List and O(1) for a HashSet
    • Any is simply O(n)
    0 讨论(0)
  • 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<TSource>(this IEnumerable<TSource> source, TSource value)
    {
        ICollection<TSource> collection = source as ICollection<TSource>;
        if (collection != null)
        {
            return collection.Contains(value);
        }
        return source.Contains<TSource>(value, null);
    }
    

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

    public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        foreach (TSource local in source)
        {
            if (predicate(local))
            {
                return true;
            }
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题