Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Between Enum Values in C# [duplicate]

Tags:

c#

enumeration

Possible Duplicate:
How to enumerate an enum?

Suppose that i have an enumeration like that:

public enum Cars
{
    Audi = 0,
    BMW,
    Opel,
    Renault,
    Fiat,
    Citroen,
    AlfaRomeo,
}

Do i have a chance to iterate between Opel and Citroen? I want to give these values as parameters of a method.

like image 982
sanchop22 Avatar asked May 08 '12 13:05

sanchop22


3 Answers

This will work:

for(Cars car=Cars.Opel; car<=Cars.Citroen; car++)
{
  Console.WriteLine(car);
}

but you have to make sure that the start value is less than the end value.

EDIT
If you don't hardcode the start and end, but supply them as parameters, you need to use them in the correct order. If you just switch "Opel" and "Citroen", you will get no output.

Also (as remarked in the comments) the underlying integer values must not contain gaps or overlaps. Luckily if you do not specify values yourself (even the '=0' is not needed), this will be the default behaviour. See MSDN:

When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1.

like image 90
Hans Kesting Avatar answered Oct 07 '22 09:10

Hans Kesting


You can use the following code to loop trough an enum:

string[] names = Enum.GetNames(typeof(Cars));
Cars[] values = (MyEnum[])Enum.GetValues(typeof(Cars));

for( int i = 0; i < names.Length; i++ )
{
    print(names[i], values[i]);
}

If you know that you want to start at Opel and go to Citroen, you set the start and end values of i to the correct index in your array.

That would look something like this:

  string[] names = Enum.GetNames(typeof(Cars));
  Cars[] values = (Cars[])Enum.GetValues(typeof(Cars));

  int start = names.ToList().IndexOf("Opel");
  int end = names.ToList().IndexOf("Citroen") + 1;

  for (int i = start; i < end; i++)
  {
      Console.WriteLine(names[i] + ' ' + values[i]);
  }
like image 29
Wouter de Kort Avatar answered Oct 07 '22 10:10

Wouter de Kort


Also, using LINQ:

var values = (from e in Enum.GetValues(typeof(Cars)) as Cars[]
              where e >= Cars.Opel && e <= Cars.Citroen
              select e);
// the same as above, but using lambda expressions
// var values = (Enum.GetValues(typeof(Cars)) as Cars[]).Where(car => car >= Cars.Opel && car <= Cars.Citroen); 

foreach(Cars c in values) Console.WriteLine(c);
like image 22
moribvndvs Avatar answered Oct 07 '22 09:10

moribvndvs