我基本上有一個枚舉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);
}
見 http://msdn.microsoft.com/en-us/library/kxydatf9.aspx 對於可拋出的異常。 – dugas 2010-02-10 02:29:41