What is the difference between Contains and Any in LINQ?

前端 未结 5 1551
孤独总比滥情好
孤独总比滥情好 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

提交回复
热议问题