3

Whole enum iteration

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
    // ...
}

But how To iterate a bitwise enum Instance?

Suit mySuits = Suit.Hearts | Suit.Diamonds;
// How to now iterate mySuits, which should loop twice instead of four times?
Community
  • 1
  • 1
Cel
  • 5,879
  • 8
  • 66
  • 107

4 Answers4

6

Assuming Suit is a bitwise enum with no overlapping values, then this would be sufficient:

var availableSuits = Enum.GetValues(typeof(Suit)).Cast<Enum>();
foreach (Suit suit in availableSuits.Where(mySuits.HasFlag)) {
    // ...
}

If it needs to be fast, or if it needs to ignore composite values or a zero value, then you should probably instead check successive powers of two in a for loop and identify which values match that way.

mqp
  • 64,209
  • 13
  • 90
  • 122
  • 1
    your `Where` did not work for me until i replaced it with Fischermaens `item => mySuits.HasFlag(item)` . thanks for the solution!: i think both answers are pretty much the same, but i will accept yours for the extra comments and for being first :) – Cel Nov 08 '11 at 18:48
2

My suggestion:

foreach (var item in Enum.GetValues(typeof(Suit)).Cast<Enum>().Where(item => mySuit.HasFlag(item)))
{
    // Do something
}
Fischermaen
  • 11,334
  • 1
  • 35
  • 55
1

Not perfect (boxing), but it does the job...

/// <summary>
/// Return an enumerators of input flag(s)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static IEnumerable<T> GetFlags<T>(this T input)
{
    foreach (Enum value in Enum.GetValues(input.GetType()))
    {
        if ((int) (object) value != 0) // Just in case somebody has defined an enum with 0.
        {
            if (((Enum) (object) input).HasFlag(value))
                yield return (T) (object) value;
        }
    }
}

Usage:

    FileAttributes att = FileAttributes.Normal | FileAttributes.Compressed;
    foreach (FileAttributes fa in att.GetFlags())
    {
        ...
    }
Eric Ouellet
  • 9,516
  • 8
  • 69
  • 100
-3

An enum is just a value type - it is not iterable.

Frep D-Oronge
  • 2,570
  • 2
  • 26
  • 27
  • im guessing you gave a downvote to my question (even though i did not downvote you)? above posts show that it is iterable, so im not sure as to the reasons of your assumed downvote ... – Cel Nov 08 '11 at 18:51
  • in case you are not familiar with bitwise enums, which are useful in certain situations (as all things), then [here is a post](http://www.dotnetperls.com/enum-flags) – Cel Nov 08 '11 at 18:56
  • Frep D-Oronge: you're wrong, they are iterable using LINQ (See mquader and my answer) – Fischermaen Nov 08 '11 at 20:02