如何通过Enum执行LINQ查询? [英] How to perform LINQ query over Enum?
问题描述
以下是我的枚举器列表
:
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.
这就是我的意思到目前为止:
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();
}
但是,我认为代码有点混乱,不是正确的方法将已过滤的枚举
列表绑定到 Combobox
。
有人可以建议一种更强大的方法吗?
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?
我可能需要更改选择顺序。因此,我需要一个通用的解决方案,该解决方案不仅要获取前X个状态。
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.
推荐答案
好吧,如果您要要硬编码应该在列表中的项目,为什么不这样做呢?
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
};
}
您还可以处置 List< T>
并返回数组本身。只要您知道这些是您想要的物品,就不需要Linq。
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.
这篇关于如何通过Enum执行LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!