开发者

Loop through enumeration

What is best way to loop through an enumeration looking for a matching value?

string match = "A";

enum Sampl开发者_开发技巧e { A, B, C, D }

foreach(...) {
  //should return Sample.A
}


You're looking for Enum.Parse:

Sample e = (Sample)Enum.Parse(typeof(Sample), match);

You can loop through the values by calling Enum.GetValues or Enum.GetNames.


Enum.Parse(typeof(Sample), "A");


Use Enum.Parse

(Sample)Enum.Parse(typeof(Samples), "A"); //returns Sample.A


public Sample matchStringToSample(string match)
{
    return (Sample)Enum.Parse(typeof(Sample), match);
}

You'd have to handle the case where the string match is not a valid enum value. Enum.Parse throws an ArgumentException in that case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜