Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

c# - How to perform LINQ query over Enum?

Below is my Enumerator List:

public enum StatusEnum
{
    Open = 1,
    Rejected = 2,
    Accepted = 3,
    Started = 4,
    Completed = 5,
    Cancelled = 6,
    Assigned = 7
}

I need to bind this to a Combobox, but, only show a few specific statuses and ignore the rest.

This is what I have so far:

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

However, I feel that the code is little messy and is not a correct approach to bind filtered Enum list to a Combobox. Can anyone suggest a more robust way of doing this?

Update

I might need to change the Order of selection. So I need a generic solution which doesn't only get the first X number of statuses.

question from:https://stackoverflow.com/questions/17091917/how-to-perform-linq-query-over-enum

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well if you're going to hard code the items that should be in the list anyway, why not just do this:

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

You could also dispose of the List<T> and just return the array itself. As long as you know these are the items you want, then there's no need for Linq.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...