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 w开发者_StackOverflowith the if statement above.
Update
How can I build a list of ints representing the flags set in the enum e1
?
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.)
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)
if((int)(e1 & se) > 0)
That should do it
this would work
if((int)se==(int)SomeEnum.A||(int)se==(int)SomeEnum.B )
{
list.Add( (int)se );
}
精彩评论