Home c# Set whether an element is present in an array (C #)

Set whether an element is present in an array (C #)

Author

Date

Category

There is a variable containing a name, for example:

string name = "Kolya";

and an array containing names, for example:

string [] array = {"Kolya", "Fedya", "Frosya", "Motya"};

How to check if the name specified in a variable is in the array?


Answer 1, authority 100%

Can be done in several different ways, for example:

string name = "Kolya";
string [] array = {"Kolya", "Fedya", "Frosya", "Motya"};
// Method # 1
foreach (string str in array)
{
  if (str == name)
  {
    Console.WriteLine (string.Format ("The word '{0}' is contained in the array", name));
    // to do something ...
  }
}
// Method # 2
if (array.Any (str = & gt; str == name))
{
  Console.WriteLine (string.Format ("The word '{0}' is contained in the array", name));
  // to do something ...
}
// Method # 3
if (array.Contains (name))
{
  Console.WriteLine (string.Format ("The word '{0}' is contained in the array", name));
  // to do something ...
}

A list of useful MSDN links to explore:

  1. foreach, in (C # Reference)
  2. Enumerable.Any – method
  3. String.Contains – method
  4. Intersect method

Answer 2, authority 32%

You can use the HashSet class and using the Contains method

string name = "Kolya";
string [] array = {"Kolya", "Fedya", "Frosya", "Motya"};
var hash = new HashSet & lt; string & gt; (array);
if (hash.Contains (name))
{
  Console.WriteLine (string.Format ("The word '" + name + "' is contained in the array"));
  // ...
}

Answer 3, authority 21%

Via LINQ

bool result = array.Any (n = & gt; n == name);

Answer 4, authority 21%

To find out whether an array contains the required element or not, you can use the functions
Array.Exists or Array.IndexOf :

contains = Array.IndexOf (array, name)! = -1;

or

contains = Array.Exists (array, v = & gt; v == name);

Answer 5, authority 7%

Via List & lt; & gt; (net 2.0)

List & lt; string & gt; lst = new List & lt; string & gt; (array);
bool result = (lst.IndexOf (name) & gt; = 0);

can be simplified

((IList & lt; string & gt;) array) .IndexOf (name);

Answer 6, authority 4%

using System.Linq;
string name = "Kolya";
string [] array = {"Kolya", "Fedya", "Frosya", "Motya"};
if (array .Contains (name))
{
  Action ();
}

Use Linq, there is a Contains method, and how to get what you want + the code looks more concise.
If used without Linq Conatins, then an error is possible (it was like this for me + it looks at the presence of a given substring in the string

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions