Check if a value is in an array (C#)

C#.NetArraysString

C# Problem Overview


How do I check if a value is in an array in C#?

Like, I want to create an array with a list of printer names.

These will be fed to a method, which will look at each string in turn, and if the string is the same as a value in an array, do that action.

For example:

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
foreach (p in printer)
{
   PrinterSetup(p);     
}

These are the names of the printers, they are being fed to the PrinterSetup method.

PrinterSetup will look sort of like this (some pseudocode):

public void PrinterSetup(printer)
{
   if (printer == "jupiter") 
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

How do I format if (printer == "jupiter") in a way that C# can recognize?

C# Solutions


Solution 1 - C#

Add necessary namespace

using System.Linq;

Then you can use linq Contains() method

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
    Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}

Solution 2 - C#

string[] array = { "cat", "dot", "perls" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perls");
bool b = Array.Exists(array, element => element == "python");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

// Display bools.
Console.WriteLine(a); // true
Console.WriteLine(b); // false
Console.WriteLine(c); // true
Console.WriteLine(d); // false

Solution 3 - C#

Add using System.Linq; at the top of your file. Then you can do:

if ((new [] {"foo", "bar", "baaz"}).Contains("bar"))
{

}  

Solution 4 - C#

    public static bool Contains(Array a, object val)
    {
        return Array.IndexOf(a, val) != -1;
    }

Solution 5 - C#

Something like this?

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
PrinterSetup(printer);

// redefine PrinterSetup this way:
public void PrinterSetup(string[] printer)
{
    foreach (p in printer.Where(c => c == "jupiter"))
    {
        Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
    }
}

Solution 6 - C#

Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.

I would like to add an extending answer referring to different C# versions and because of two reasons:

  • The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.

  • No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).

Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.

Since .NET 3.5 there also exists a generic method Array<T>.Exists() :

public void PrinterSetup(string[] printer)
{
   if (Array.Exists(printer, x => x == "jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same/similar ".Contains" as for strings for all arrays without including Linq:

// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
   if (printer.ArrayContains("jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

public static bool ArrayContains<T>(this T[] thisArray, T searchElement)
{
   // If you want this to find "null" values, you could change the code here
   return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}

In this case this ArrayContains() method is used and not the Contains method of Linq.

The elsewhere mentioned .Contains methods refer to List<T>.Contains (since C# 2.0) or ArrayList.Contains (since C# 1.1), but not to arrays itself directly.

Solution 7 - C#

You are just missing something in your method:

public void PrinterSetup(string printer)
{
   if (printer == "jupiter") 
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
   }
}

Just add string and you'll be fine.

Solution 8 - C#

Not very clear what your issue is, but it sounds like you want something like this:

    List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );

    if( printer.Exists( p => p.Equals( "jupiter" ) ) )
    {
        ...
    }

Solution 9 - C#

Consider using HashSet<T> Class for the sake of lookup performance:

> This method is an O(1) operation. > > — HashSet<T>.Contains Method (T), MSDN.

For example:

class PrinterInstaller
{
    private static readonly HashSet<string> PrinterNames = new HashSet<string>
        {
            "jupiter", "neptune", "pangea", "mercury", "sonic"
        };

    public void Setup(string printerName)
    {
        if (!PrinterNames.Contains(printerName))
        {
            throw new ArgumentException("Unknown printer name", "printerName");
        }
        // ...
    }
}

Solution 10 - C#

I searched now over 2h to find a nicely way how to find duplicates in a list and how to remove them. Here is the simplest answer:

//Copy the string array with the filtered data of the analytics db into an list
// a list should be easier to use
List<string> list_filtered_data = new List<string>(analytics_db_filtered_data);

// Get distinct elements and convert into a list again.
List<string> distinct = list_filtered_data.Distinct().ToList();

The Output will look like this: Duplicated Elements will be removed in the new list called distinct!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteven MatthewsView Question on Stackoverflow
Solution 1 - C#DmytroView Answer on Stackoverflow
Solution 2 - C#user2667398View Answer on Stackoverflow
Solution 3 - C#GuestView Answer on Stackoverflow
Solution 4 - C#Rezo MegrelidzeView Answer on Stackoverflow
Solution 5 - C#code4lifeView Answer on Stackoverflow
Solution 6 - C#PhilmView Answer on Stackoverflow
Solution 7 - C#user195488View Answer on Stackoverflow
Solution 8 - C#Brandon MoretzView Answer on Stackoverflow
Solution 9 - C#Sergey Vyacheslavovich BrunovView Answer on Stackoverflow
Solution 10 - C#Ricardo FercherView Answer on Stackoverflow