简体   繁体   中英

How to cast int value to list int value of Flag enums

I have this flag enum:

public enum DataAccessPoliceis
{
      None = 0,
      A = 1,
      B = 2,
      C = 4, 
      D = 8, 
      E = B | C | D, // 14
      All = A | E // 15
}

I want to get int value (or list of int values for complex enum item) from int value:

int x = 9; // enum items => D | A
List<int> lstEnumValues = ???
// after this line ...
// lstEnumValues = { 1, 8 }
// and for x = 15
// lstEnumValues = { 1, 2, 4, 8, 14, 15 }

What's your solution for this question?

Use can use the class Enum and the GetValues method. Try it Like this:

var lstEnumValues = new List<int>(Enum.GetValues(typeof(DataAccessPolicies)).Cast<int>());

The output is:

输出结果

Hope this helps.

Answer of my question:

var lstEnumValues = new List<int>Enum.GetValues(typeof(DataAccessPoliceis)).Cast<int>())
.Where(enumValue => enumValue != 0 && (enumValue & x) == enumValue).ToList();

@dyatchenko and @Enigmativity thank you for your responses.

Try:

var lstEnumValues =
    ((DataAccessPoliceis[])(Enum.GetValues(typeof(DataAccessPoliceis))))
    .Where(v => v.HasFlag(x))
    .Select(v => (int)v)  // omit if enum values are OK
    .ToList();            // omit if List<> not needed

For these scenarios I prefer using extension methods.

public static IEnumerable<Enum> ToEnumerable(this Enum input)
{
    foreach (Enum value in Enum.GetValues(input.GetType()))
        if (input.HasFlag(value) && Convert.ToInt64(value) != 0)
            yield return value;
}

Usage:

 var lstEnumValues = flagEnum.ToEnumerable().Select(x => Convert.ToInt32(x)).ToList();  

Yet another approach:

As flags are only combinations of exponentiated numbers to base 2 and every natural number has exactly one representation in the binary number-system, it is actually sufficient to consider only the binary representation (not the enum itself). After the conversion to the binary representation, there is only to convert all places with a "1" back to the decimal-system (and to omit the zeros) and to output in form of a list.

With a little help from LINQ this can be written like this:

int value = 9;

//convert int into a string of the the binary representation
string binary = Convert.ToString(value, 2);

var listOfInts = binary

    //convert each binary digit back to a decimal
    .Select((v, i) => Int32.Parse(v.ToString()) * Math.Pow(2, binary.Length-i-1))   
    
    //filter decimal numbers that are based on the "1" in binary representation
    .Where(x => x > 0)  

     //you want the integers in ascending order
    .OrderBy(x => x);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM