简体   繁体   中英

search array of strings in an enum and return true if available

I have an enumeration:

    [Flags]
    public enum MyColours{
    Red = 1,
    Green = 2, 
    Blue = 4,
    Yellow = 8,
    Orange = 16,
    };

Now i have a list of strings:

    string[] colour = new string { "Red", "Orange", "Blue"};

I want to able to return true for the stirngs which match with enums.

The question suks.

I think you want to see if a value in your enum matches a parameter, and returns true dependant on that parameter?

bool IsInsideEnum(string value) {
  foreach (var enumVal in Enum.GetValues(typeof(MyColors)) 
    if(Enum.GetName(typeof(MyColors), enumVal) == value) 
      return true;
  return false;
}

your question is really vague. But i am assuming you mean something like this

if (colour[0] == Enum.GetName(typeof(MyColors), 1)) //"Red" == "Red"
{
   return true;
}

Enum.GetName(typeof(MyColors), 1) is what you are looking for

typeof(enumName) followed by enumIndex

   List<string> colour = new List<String>{ "Red", "Orange", "Blue" };
   List<string> enumColors = Enum.GetNames(typeof(MyColours)).ToList();
   foreach (string s in enumColors)
   {
          if (colour.Exists(e => e == s))
              return true;
          else
              return false;

   }

hope this helps

使用Enum.GetName(Enum,int)获得枚举的字符串

BETTER ANSWER - LESS VERBOSE:

var values = Enum.GetNames(typeof(MyColours)).ToList();

string[] colour = new string[] { "Red", "Orange", "Blue" };

List<string> colourList = colours.ToList();

ConatainsAllItems(values, colourList);

public static bool ContainsAllItems(List<T> a, List<T> b)
{
    return !b.Except(a).Any();
}

This should return true if they have matching values

You could use the Enum.TryParse method, something like this:

MyColours c;
from s in colour select new {Value = s, IsAvailable = Enum.TryParse(s, true, out c)}

Or you can do a loop and figure that out for each value in the array using that method.

Quite direct, put Enum.IsDefined for that:

   string[] colour = new string[] { "Red", "Orange", "Blue", "White" };

   var result = colour
     .Select(c => Enum.IsDefined(typeof(MyColours), c));

Test

  // True, True, True, False
  Console.Write(String.Join(", ", result));

Try this,

foreach(string s in colour)
       { 
           Enum.GetNames(typeof(MyColours)).Contains(s); 
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM