0

Let's suppose I have a very simple IEnumerable that looks like this:

IEnumerable<string> foo = new[] { "Apple", null, "Orange" };

I would like to check if it contains a null item. Based on what I found with Google, I can do this as follows:

bool containsNull = foo.Any(item => item == null);

What about the Enumerable.Contains method? The following seems pretty obvious to me, but I've never seen it this way:

bool containsNull = foo.Contains(null);

Is there any problem with the previous expression that results in the Enumerable.Any method used instead?

Akira
  • 4,385
  • 3
  • 24
  • 46
  • 1
    No, and it should be faster as well – canton7 Feb 26 '20 at 10:24
  • 2
    Please look at this [topic](https://stackoverflow.com/questions/4445219/linq-ring-any-vs-contains-for-huge-collections) – Stefano Cavion Feb 26 '20 at 10:26
  • Does this answer your question? [LINQ Ring: Any() vs Contains() for Huge Collections](https://stackoverflow.com/questions/4445219/linq-ring-any-vs-contains-for-huge-collections) – Selim Yildiz Feb 26 '20 at 10:26
  • 2
    I would use Contains for checking if element is in array or not, and would use Any when need to check something more complex, for example, foo.Any(item => item != null && item[0] == 'A' && item.Length == 5) – Arsen Mkrtchyan Feb 26 '20 at 10:39

2 Answers2

3

It's true, in most of the cases Contains(null) will do the work. But there is a vulnerability for ArgumentNullException. An example can be:

string foo = "foo";
bool containsNull = foo.Contains(null); //throws exception

In your case, you've already set the generic type as string so it is safe to use Contains.

Akira
  • 4,385
  • 3
  • 24
  • 46
Indrit Kello
  • 1,293
  • 8
  • 19
  • 1
    Note that in the case of `string`, `foo.Contains()` looks for a substring while `foo.AsEnumerable().Contains()` looks for a contained char (and won't compile if you pass null). – Matthew Watson Feb 26 '20 at 10:47
0

The "Contains" operator checks whether a specified element exists in the collection or not and returns a boolean.

"Any" checks whether any element satisfy given condition or not? In the following example, Any operation is used to check whether any student is teen ager or not.

In this case is better use "ANY"

yo can to visit https://www.tutorialsteacher.com/linq/linq-quantifier-operators