从枚举中获取值

时间:2013-04-15 13:06:43

标签: c# enums

我需要找到enum DaysOfTheWeek过滤的List<int> daysId值并返回过滤的枚举

我的枚举:

[Flags]
public enum DaysOfTheWeek
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64,
    AllDays = 127,
}

-

var allValues = Enum.GetValues(typeof(DaysOfTheWeek));

我的整数列表:

List<int> daysId = new List<int> {1,3};

3 个答案:

答案 0 :(得分:1)

var filtered = daysId.Select(d => (DaysOfTheWeek)d);

答案 1 :(得分:0)

不确定您的问题。像这样的东西?

var filtered  = daysId.Select(d=>(DaysOfTheWeek)(1<<(d-1))).ToList();

答案 2 :(得分:0)

也许我过于复杂,但请检查一下:

int[] daysId = new int[] { 1, 3,48,127 };

Dictionary<int, List<DaysOfTheWeek>> result = new Dictionary<int, List<DaysOfTheWeek>>();

foreach (int id in daysId)
{
    result[id] = new List<DaysOfTheWeek>();
    BitArray ba = new BitArray(new int[]{id});
    for (int i=0;i<ba.Length;i++)
    {
        if (ba[i])
        {
            result[id].Add((DaysOfTheWeek)(1 << i));
            Console.WriteLine((DaysOfTheWeek)(1 << i));
         }                    
     }
    Console.WriteLine("id-" + id + " > " + (DaysOfTheWeek)id);                
}

Console.ReadKey();

检查输出并查看它是否是您想要的。如果您愿意,可以使用直接转换为星期几(DaysOfTheWeek)id,也可以单独获取每个DaysOfTheWeek。我在上面做了两件事。