Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Contains and Any in LINQ?

Tags:

c#

linq

What is the difference between Contains and Any in LINQ?

like image 576
user2202911 Avatar asked May 07 '14 19:05

user2202911


2 Answers

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

like image 191
BradleyDotNET Avatar answered Sep 26 '22 05:09

BradleyDotNET


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); 
like image 29
Habib Avatar answered Sep 22 '22 05:09

Habib