views:

285

answers:

3

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);
            }
+7  A: 

Are you trying to convert a string to an instance of WorkingDays? If so use Enum.Parse:

WorkingDays day = (WorkingDays)Enum.Parse(typeof(WorkingDays), "monday", true);

Here we are using the overload Enum.Parse(Type, string, bool) where the bool parameter indicates whether or not to ignore case.

On a side note, you should rename WorkingDays to WorkingDay. Look at like this. When you have an instance of WorkingDay, say,

WorkingDay day = WorkingDay.Monday;

note that day is a working day (thus WorkingDay) and not working days (thus not WorkingDays). For additional guidelines on naming enumerations, see Enumeration Type Naming Guidelines.

Jason
+2  A: 

Here's a non-Linq way.

EDIT: It's basically Jason's way. He posted before me. Give the kudos to him.

Aaron Daniels
+1 for you anyways :)
ram
+1  A: 

use IsDefined link text

SilverNight
Actually, using IsDefined isn't the best way to go for range checks like this. (Framework Design Guidelines, 2nd Ed., pp 181-182). Enum.IsDefined is deceptively expensive due to a lot of reflection and it isn't guaranteed to always yield the correct results for the call site.
Scott Dorman