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);
}
Are you trying to convert a
stringto an instance ofWorkingDays? If so useEnum.Parse:Here we are using the overload
Enum.Parse(Type, string, bool)where theboolparameter indicates whether or not to ignore case.On a side note, you should rename
WorkingDaystoWorkingDay. Look at like this. When you have an instance ofWorkingDay, say,note that
dayis a working day (thusWorkingDay) and not working days (thus notWorkingDays). For additional guidelines on naming enumerations, see Enumeration Type Naming Guidelines.