Germ
Germ

Reputation: 6540

Loop through enumeration

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
}

Upvotes: 5

Views: 1289

Answers (4)

John Källén
John Källén

Reputation: 7973

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.

Upvotes: 0

Use Enum.Parse

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

Upvotes: 0

Jerod Venema
Jerod Venema

Reputation: 44642

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

Upvotes: 0

SLaks
SLaks

Reputation: 888047

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.

Upvotes: 11

Related Questions