LINQ&枚举作为 IQueryable
我基本上有一个枚举
public enum WorkingDays
{
Monday, Tuesday, Wednesday, Thursday, Friday
}
,想与输入进行比较,输入恰好是一个字符串
//note lower case
string input = "monday";
我能想到的最好的事情就是这样
WorkingDays day = (from d in Enum.GetValues(typeof(WorkingDays)).Cast<WorkingDays>()
where d.ToString().ToLowerInvariant() == input.ToLowerInvariant()
select d).FirstOrDefault();
有没有更好的方法可以做到这一点?
编辑:谢谢亚伦和杰森.但是如果解析失败怎么办?
if(Enum.IsDefined(typeof(WorkingDay),input))//cannot compare if case is different
{
WorkingDay day = (WorkingDay)Enum.Parse(typeof(WorkingDay), input, true);
Console.WriteLine(day);
}
I basically have an enum
public enum WorkingDays
{
Monday, Tuesday, Wednesday, Thursday, Friday
}
and would like to do a comparison against an input, which happens to be a string
//note lower case
string input = "monday";
The best thing I could come up with was something like this
WorkingDays day = (from d in Enum.GetValues(typeof(WorkingDays)).Cast<WorkingDays>()
where d.ToString().ToLowerInvariant() == input.ToLowerInvariant()
select d).FirstOrDefault();
Is there any better way to do it ?
Edit: Thanks Aaron & Jason. But what if the parse fails ?
if(Enum.IsDefined(typeof(WorkingDay),input))//cannot compare if case is different
{
WorkingDay day = (WorkingDay)Enum.Parse(typeof(WorkingDay), input, true);
Console.WriteLine(day);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否正在尝试将
string
转换为WorkingDays
的实例?如果是这样,请使用Enum.Parse
< /a>:这里我们使用重载
Enum.Parse(Type , string, bool)
其中bool
参数指示是否忽略大小写。另外,您应该将
WorkingDays
重命名为WorkingDay
。看看像这样。例如,当您有WorkingDay
的实例时,请注意
day
是工作日(因此WorkingDay
),而不是工作日(因此不是 <代码>工作日)。有关命名枚举的其他准则,请参阅枚举类型命名准则< /a>.Are you trying to convert a
string
to an instance ofWorkingDays
? If so useEnum.Parse
:Here we are using the overload
Enum.Parse(Type, string, bool)
where thebool
parameter indicates whether or not to ignore case.On a side note, you should rename
WorkingDays
toWorkingDay
. Look at like this. When you have an instance ofWorkingDay
, say,note that
day
is a working day (thusWorkingDay
) and not working days (thus notWorkingDays
). For additional guidelines on naming enumerations, see Enumeration Type Naming Guidelines.这是一种非 Linq 方式。
编辑:这基本上是杰森的方式。他在我之前发帖。给他点赞。
Here's a non-Linq way.
EDIT: It's basically Jason's way. He posted before me. Give the kudos to him.
使用 IsDefined
链接文本
use IsDefined
link text
我能够通过填充列表集合将枚举转换为 IQueryable。
I was able to convert an enum into a IQueryable by populating a List collection.