I want convert the name of days in a week (Monday,Tuesday...) into the number of days in a week (Monday=1, Tuesday=2,...)
问题:
回答1:
You mention using "array method". Perhaps you mean looking up the index in a constant pre-defined array/collection.
public static int ConvertDayOfWeek(string day) {
List<string> days = new List<string>{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
return days.IndexOf(day);
}
回答2:
You can use Enum.Parse
along with the DayOfWeek
enum to parse a string that has a day of the week into an integer value (which is itself just a label that wraps an integer) that corresponds to the appropriate day of the week. If you really need an integer specifically, and not an enum, you can cast that enum to an int
to get its underlying value.
回答3:
You could create an enum
that contains all possible days, and then use Enum.Parse
and cast it to an int
. Though this is a bit of a "heavy hammer." Your other option is to use a switch
or series of if
statements to determine the number.
回答4:
If you just want for days of weeks is simple in c# using
int numberDate = (int)DateTime.Now.DayOfWeek;
which will give you the number of the day
string stringDay = DateTime.Now.DayOfWeek.ToString();
which will give you the string name of the week.
回答5:
Another idea:
If you are going to have a structure which maps string to int, simply you may use Dictionary<string,int>
like this:
Dictionary<string, int> days = new Dictionary<string, int>();
days.Add("Monday",1);
days.Add("Tuesday",2);
//...
var number = days["Monday"]; //Result: 1