views:

176

answers:

4

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
}
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.

John Källén
If you expect it to fail sometimes, use Enum.TryParse()
Nelson
@Nelson: `Enum.TryParse` is new to .Net 4.0.
SLaks
+9  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.

SLaks
A: 
Enum.Parse(typeof(Sample), "A");
jvenema
A: 

Use Enum.Parse

(Sample)Enum.Parse(typeof(Samples), "A"); //returns Sample.A
BlueRaja - Danny Pflughoeft
@Mark Byers, it is just an example statement. Give him a break.
AMissico