1

I have an array of integers:

var a = [1,2,3,4];

How can I find out if a number such as the number 1 exists in this array without doing a for loop?

I saw that C# has an Array.Exists(T) method but I am not sure how to use it. If this is a good way to do it then I would appreciate some advice.

3 Answers 3

3

Better to user Contains or Any but you asked for Exists so:

int[] arr = {1,2,3,4};


Exists:

bool a = Array.Exists(arr, elem => elem == 1); // true
bool b = Array.Exists(arr, elem => elem == 5); // false

Contains:

  bool a = arr.Contains(1); // true
  bool b = arr.Contains(5); // false

Any:

 bool a = arr.Any(elem => elem == 1); // true
 bool b = arr.Any(elem => elem == 5); // false
Sign up to request clarification or add additional context in comments.

Comments

1

Since C# arrays can be used in LINQ expressions, you can do this:

bool hasOne = a.Any(n => (n == 4));

You need to add using System.Linq in order for this to compile.

Comments

1

Using Linq Contains you can check for the existence of int,

var intVar = 1;
var exists = a.Contains(intVar);

1 Comment

@marifemac the best way to check it is to try it yourself! dotnetfiddle.net/0PR3iT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.