簡體   English   中英

如何將 int 值轉換為列出 Flag 枚舉的 int 值

[英]How to cast int value to list int value of Flag enums

我有這個標志枚舉:

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

我想從 int 值中獲取 int 值(或復雜枚舉項的 int 值列表):

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 }

你對這個問題的解決方案是什么?

使用可以使用類EnumGetValues方法。 試試這樣:

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

輸出是:

輸出結果

希望這可以幫助。

回答我的問題:

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

@dyatchenko 和 @Enigmativity 感謝您的回復。

嘗試:

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

對於這些場景,我更喜歡使用擴展方法。

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;
}

用法:

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

還有一種方法:

由於標志只是以 2 為底的取冪數的組合,並且每個自然數在二進制數系統中都只有一種表示形式,因此實際上只考慮二進制表示形式(而不是枚舉本身)就足夠了。 轉換為二進制表示后,只需將所有帶“1”的位置轉換回十進制(並省略零)並以列表形式輸出。

在 LINQ 的幫助下,可以這樣寫:

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);   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM