我基本上有一个枚举
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();
有更好的方法吗?
编辑:谢谢Aaron和Jason。但是如果解析失败怎么办?
if(Enum.IsDefined(typeof(WorkingDay),input))//cannot compare if case is different
{
WorkingDay day = (WorkingDay)Enum.Parse(typeof(WorkingDay), input, true);
Console.WriteLine(day);
}