How to perform LINQ query over Enum?

前端 未结 6 587
梦如初夏
梦如初夏 2021-02-03 19:42

Below is my Enumerator List:

public enum StatusEnum
{
    Open = 1,
    Rejected = 2,
    Accepted = 3,
    Started = 4,
    Completed = 5,
    Canc         


        
6条回答
  •  盖世英雄少女心
    2021-02-03 19:50

    First, if possible, I'd make your enum values powers of 2, so they could be OR'd together.

    public enum StatusEnum
    {
        Open = 1,
        Rejected = 2,
        Accepted = 4,
        Started = 8,
        Completed = 16,
        Cancelled = 32,
        Assigned = 64
    }
    

    Then you could do something like this:

    public static List StatusList()
    {
        var statusesToShow = Activity.StatusEnum.Open | Activity.StatusEnum.Rejected | Activity.StatusEnum.Accepted | Activity.StatusEnum.Started;
    
        return Enum
            .GetValues(typeof(Activity.StatusEnum))
            .Cast()
            .Where(x => (x & statusesToShow) == x)
            .ToList();
    }
    

    EDIT: In light of the fact that you can't change the enum values, I'd just recommend you use something like:

    public static List StatusList()
    {
        return new List {
            Activity.StatusEnum.Open, 
            Activity.StatusEnum.Rejected, 
            Activity.StatusEnum.Accepted, 
            Activity.StatusEnum.Started
        };
    }
    

提交回复
热议问题