I cant find a way to express this method into a generic method. Target is to use any flagged enum. Would be great, if someone could help.
class Program
{
[Flags]
public enum MyRights
{
Read, Write, Delete, CreateChild, FullRights
}
static void Main(string[] args)
{
MyRights myRights = new MyRights();
myRights = MyRights.Read | MyRights.Delete;
var kvpList = GetList(myRights);
Console.ReadKey();
}
private static List<KeyValuePair<string, int>> GetList(MyRights myRights)
{
return Enum.GetValues(typeof(MyRights)).Cast<MyRights>()
.Where((enumValue) => myRights.HasFlag(enumValue))
.Select((enumValue) =>
new KeyValuePair<string, int>(enumValue.ToString(), (int)enumValue))
.ToList();
}
}
Best regards Tzwenni
PS: Not regarding NULL check etc. at the moment.
UPDATE Solution
thx to @Flydog57
initialize the values
1st important hint ;)
public enum MyRights
{
Read = 0x01, Write = 0x02, Delete = 0x04, CreateChild = 0x08
}
Then: I couldn't cast value to int. But using HashCode works fine:
private static List<KeyValuePair<string, int>> GetListGeneric<TEnum>(TEnum myRights)
where TEnum : Enum
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>()
.Where((enumValue) => myRights.HasFlag(enumValue))
.Select((enumValue) =>
new KeyValuePair<string, int>(enumValue.ToString(), enumValue.GetHashCode())
).ToList();
}
Extension method
static List<TEnum> ToList<TEnum>(this TEnum myRights) where TEnum : Enum
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Where((enumValue) =>
myRights.HasFlag(enumValue)).Select((enumValue) => enumValue).ToList();
}