Search code examples
c#stringlistcollections

How to verify the presence of a string in a constant list of strings


This should be easy, but I don't find the correct syntax: I would like to know if my name is present in a contant list of strings.

These are my attempts:

// first idea
if (Destination.Name in {"MA", "MB", "MC", "MD", "ME", "MF", "MG"})

// after some searching
if IndexOf(new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }, Destination.Name)

... but none of them seems to work.

What's the easiest way to get this done in C#?

Thanks in advance


Solution

  • If I understand you right, you are looking for Destination.Name in "MA", "MB", "MC", "MD", "ME", "MF", "MG" (i.e. if Destination.Name is MA or MB etc.):

    if (new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }.Contains(Destination.Name)) 
    {
      ...
    }
    

    Same for IndexOf: we check if Destination.Name index within the array is not negative:

    // Either use List, or ugly
    // if (Array.IndexOf(new string[] {...}, Destination.Name)) {...}
    if (new List<string> { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }
          .IndexOf(Destination.Name) >= 0) 
    {
      ...
    }
    

    Finally, in general case you can query array with a help of Linq. It's an overshoot here, but if you have a non-trivial condition, lambda function (here it is item => item == Destination.Name) could be very flexible.

    using System.Linq;
    
    ...
    
    // If the array has any item which is equal to Destination.Name 
    if (new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }
          .Any(item => item == Destination.Name))
    {
       ...
    }