5

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
}
2
  • foreach what? What exactly are you trying to test? Commented May 3, 2010 at 20:54
  • I'm looking to see if "A" exists and return the matching enumerator value Commented May 3, 2010 at 20:56

4 Answers 4

11

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Use Enum.Parse

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

1 Comment

@Mark Byers, it is just an example statement. Give him a break.
0
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.

2 Comments

If you expect it to fail sometimes, use Enum.TryParse()
@Nelson: Enum.TryParse is new to .Net 4.0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.