C# Class array - Check if match


Keywords:c# 


Question: 

So Basicly I have this class:

 class Postnumre
 {
    public static int[] PostnumberWest =
    {
        5320,6753,6534,8961,6051,8592,8643,6823,9510,5466,5610,9340,6440,7490,8963,5935,8444,7150,6210,8330,7755,6541,6852,7190,9881,8850,6091,5603,9492,5491,6857,5400,6392,7441,9998,8220,6740,7330,6535,6261,7182,5464,6310,5672,9460,8654,8740,9700,6650,6372,6622,7660,9574,7080,7650,6070,5380,8721,9330,9352,5631,8400,6320,6040,8250,5592,7361,7442,7950,6700,6701,6715,6710,6705,7997,9997,7996,9996,6720,9640,5863,9690,8762,7000,7029,9900,5871,7741,7884,6683,5600,8990,8882,7321,8464,9362,9631,8751,5591,6621,5854,9260,7323,8983,8883,5620,6752,8585,6510,6771,8500,7200,6300,5892,5884,6690,6100,7540,8370,9560,9370,8450,7362,7730,7673,8462,5463,8361,8970,8722,6094,7250,6893,6854,7400,7429,5874,8382,9850,9320,7560,8530,9800,9500,7500,6670,8543,8783,8700,6682
    };
}

From a button I want to check if it contains a given value something like this:

private void radButton6_Click(object sender, EventArgs e)
    {
        if(Postnumre.PostnumberEast.Contains("5320"))
        {

        }
    }

Thanks in advance!


3 Answers: 

The array contains ints, not strings. Just remove the quotes and you're good:

// West, not East, though I'll give you the benefit of the doubt that your Postnumre class how both members
if(Postnumre.PostnumberEast.Contains(5320))
{
    //...
}

This works (assuming you have the necessary using directives) because arrays implement IEnumerable<T>, and Contains() is an extension method on that interface. You can also do this:

if(Array.IndexOf(Postnumre.PostnumberEast, 5320) > -1)
{
    //...
} 

One more option is to use a HashSet<int> rather than an array. Then you can use the Contains() method again for your check, and performance will be better as long as your sets are larger than 10 or so items. The downside there is the initialization syntax isn't quite as clean.



private void radButton6_Click(object sender, EventArgs e)
{
      // lose the quotes, its a int array not a string array
      // also the field name is PostnumberWest not PostnumberEast
      // unless you have a field called PostnumberEast
      if(Postnumre.PostnumberWest .Contains(5320))
      {

      }
}


There is actually a method, but you have to leave the quotes beside, so that you enter an Integer.