L oop через все значения перечисления с несколькими неуникальными числами - PullRequest
0 голосов
/ 23 января 2020

У меня есть это enum:

public enum MyEnum : byte
{
    [CategoryEnum(Category.Color)]
    Red = 1,
    [CategoryEnum(Category.Color)]
    Blue = 2,

    [CategoryEnum(Category.Attributes)]
    Strong = 1,
    [CategoryEnum(Category.Attributes)]
    Weak = 2
}

Когда я пытаюсь сделать

var foo = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>()

, он вернет список вроде

{Blue, Blue, Red, Red} 

, и это не то, что я ищу. Как я могу получить фактические значения , которые мне нужны? Заранее спасибо.

1 Ответ

0 голосов
/ 23 января 2020

Вы можете получить все имена enum и отфильтровать те, которые соответствуют value

Код:

private static string LongName<T>(long value) where T : Enum {
  unchecked {
    return string.Join(" or ", Enum
      .GetNames(typeof(T))
      .Where(name => Convert.ToInt64(Enum.Parse(typeof(MyEnum), name)) == value)
      .OrderBy(name => name));
  }
}

private static string LongAttributeName<T>(long value) where T : Enum {
  unchecked {
    return string.Join(" or ", Enum
      .GetNames(typeof(T))
      .Where(name => Convert.ToInt64(Enum.Parse(typeof(MyEnum), name)) == value)
      .Select(name => typeof(T)
         .GetMember(name)
         .FirstOrDefault(mi => mi.DeclaringType == typeof(T)))
      .SelectMany(mi => mi.GetCustomAttributes<CategoryEnumAttribute>(false))
      .Select(attr => attr.Description) //TODO: Put the right property here
      .OrderBy(name => name));
  }
}

private static string[] LongNames<T>() where T : Enum {
  unchecked {
    return Enum
      .GetNames(typeof(T))
      .OrderBy(name => Convert.ToInt64(Enum.Parse(typeof(MyEnum), name)))
      .ThenBy(name => name)
      .ToArray();
  }
}

private static string[] LongNamesCombined<T>() where T : Enum {
  unchecked {
    return Enum
      .GetNames(typeof(T))
      .GroupBy(name => Convert.ToInt64(Enum.Parse(typeof(MyEnum), name)))
      .OrderBy(group => group.Key)
      .Select(group => string.Join(" or ", group.OrderBy(name => name)))
      .ToArray();
  }
}

Демонстрация:

// Single Value
Console.Write(LongName<MyEnum>(1));
// Single Value attributes
Console.Write(LongAttributeName<MyEnum>(1));
// All Values (array with 4 items)
Console.Write(string.Join(", ", LongNames<MyEnum>())); 
// All Values combined (array with 2 items)
Console.Write(string.Join(", ", LongNamesCombined<MyEnum>())); 

Результат:

Red or Strong
Color or Attributes      # <- Depends on implementation
Red, Strong, Blue, Weak
Red or Strong, Blue or Weak
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...