What is best way to loop through an enumeration looking for a matching value?
string match = "A";
enum Sample { A, B, C, D }
foreach(...) {
//should return Sample.A
}
What is best way to loop through an enumeration looking for a matching value?
string match = "A";
enum Sample { A, B, C, D }
foreach(...) {
//should return 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.
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
.
Use Enum.Parse
(Sample)Enum.Parse(typeof(Samples), "A"); //returns Sample.A