Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 280
Germ Avatar asked May 03 '10 20:05

Germ


People also ask

Can you loop through an enum?

An enum can be looped through using Enum. GetNames<TEnum>() , Enum.

Can we loop through enum in C?

you can iterate the elements like: for(int i=Bar; i<=Last; i++) { ... } Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn't really provide type safety, as you can use an int in place of an enum value and vice versa.

Can you loop through an enum C ++?

Yes. It iterates over an std::initializer_list<Item>. link.


1 Answers

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.

like image 105
SLaks Avatar answered Nov 04 '22 05:11

SLaks