I have a string of abbreviated days of week e.g. "M Tu W Th F". I need to parse it to DayOfWeek.
Let's say I've converted the string to an array of strings. How do I parse each of those values to DayOfWeek?
Is there a way to do this without a custom function?
I'm aware of the method below for standard "Monday,"Tuesday"...." but how do we use that with the above shortened format?
var EnumDay = ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), "M"));
CodePudding user response:
You can't parse those using the framework directly. Instead, you need something like a switch
statement, or a switch expression if you are using a modern version of C#. For example:
public DayOfWeek Parse(string value)
{
return value switch
{
"M" => DayOfWeek.Monday,
"Tu" => DayOfWeek.Tuesday,
"W" => DayOfWeek.Wednesday,
"Th" => DayOfWeek.Thursday,
"F" => DayOfWeek.Friday,
_ => throw new Exception("Not a valid day of the week, or maybe it's a weekend, go outside and play")
};
}
And use like this:
var day = Parse("Th");