开发者

Loop through enumeration

开发者 https://www.devze.com 2022-12-29 15:01 出处:网络
What is best way to loop through an enumeration looking for a matching value? string match = \"A\"; enum Sampl开发者_开发技巧e { A, B, C, D }

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

精彩评论

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