简体   繁体   English

在枚举中搜索字符串数组,如果可用,则返回true

[英]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. 我希望能够为与枚举匹配的标准返回true。

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? 我想您想查看枚举中的值是否与参数匹配,并根据该参数返回true?

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 Enum.GetName(typeof(MyColors), 1)是您要寻找的

typeof(enumName) followed by enumIndex typeof(enumName)后跟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 如果它们具有匹配的值,则应返回true

You could use the Enum.TryParse method, something like this: 您可以使用Enum.TryParse方法,如下所示:

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. 或者,您可以执行loop并使用该方法为数组中的每个值找出该值。

Quite direct, put Enum.IsDefined for that: 十分直接,将Enum.IsDefined为此:

   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); 
       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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