codecompleting
codecompleting

Reputation: 9611

Help building a list based on a enumeration

I have an enumeration:

public enum SomeEnum
{
  A = 2,
  B = 4,
  C = 8
  D = 16 
}

SomeEnum e1 = SomeEnum.A | SomeEnum.B

Now I want to have a List of enum values, so e1 would be:

2, 4

So I have:

List<int> list = new List<int>();

foreach(SomeEnum se in Enum.GetValues(typeof(SomeEnum)))
{

  if(.....)
  {
     list.Add( (int)se );
  }


}

I need help with the if statement above.

Update

How can I build a list of ints representing the flags set in the enum e1?

Upvotes: 2

Views: 71

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1501163

I suspect you want:

if ((e1 & se) != 0)

On the other hand, using Unconstrained Melody you could write:

foreach (SomeEnum se in Enums.GetValues<SomeEnum>())
{
    if (se.HasAny(e1))
    {
        list.Add((int) se);
    }
}

Or using LINQ:

List<int> list = Enums.GetValues<SomeEnum>()
                      .Where(se => se.HasAny(e1))
                      .Select(se => (int) se)
                      .ToList();

(It would be nice if you could use e1.GetFlags() or something to iterate over each bit in turn... will think about that for another release.)

Upvotes: 4

Ray
Ray

Reputation: 46585

Do you want to add the value if it's in e1?

Then you can use the HasFlag method in .NET 4.

if(e1.HasFlag(se))
{
    list.Add( (int)se );
}

If you're not using .net the equivilant is e1 & se == se

Also by convention you should mark your enum with the FlagsAttribute and it should be in plural form (SomeEnums)

Upvotes: 3

Nivid Dholakia
Nivid Dholakia

Reputation: 5452

this would work

if((int)se==(int)SomeEnum.A||(int)se==(int)SomeEnum.B )
      {
         list.Add( (int)se );
      }

Upvotes: 0

Jay
Jay

Reputation: 3233

if((int)(e1 & se) > 0)

That should do it

Upvotes: 0

Related Questions