假设我有天数列表:
现在用户可以从清单中选择一个或多个。我的数据库只存储天数(例如:如果用户选择了sun和mon,则值存储在数据库中是3)。现在我要显示用户天数他选择了。计算这个的公式是什么。
我应该为此写一个二进制逻辑吗?
答案 0 :(得分:3)
为工作日创建Flags枚举,将其视为位字段:
[Flags]
public enum WeekDays
{
Sun = 1,
Mon = 2,
Tue = 4,
Wed = 8,
Thu = 16,
Fri = 32,
Sat = 64
}
然后保存到数据库
WeekDays value = WeekDays.Sun | WeekDays.Mon; // Sun, Mon
从数据库中读取时,使用HasFlag方法验证值是否包含给定的工作日(如果给定位字段在枚举值中设置):
WeekDays value = ReadValueFromDatabase();
foreach(WeekDays day in Enum.GetValues(typeof(WeekDays)))
{
if (value.HasFlag(day))
// day is selected
}
这与按位操作的用法相同:
(value & day) == day
答案 1 :(得分:2)
试试这个:
[Flags]
public enum Day
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
}
Day d = Day.Friday | Day.Saturday;
Console.WriteLine(d);
Console.WriteLine((int)d);
这打印: 星期五,星期六和96
谢尔盖刚刚在我面前张贴的......
答案 2 :(得分:1)
创建一个程序,从数据库中获取剩余的总和
<pre>
private int GetRemainder(int DaySum)
{
int xRemainder = 0;
if(DaySum > 64)
xRemainder = DaySum % 64;
else if(DaySum > 32)
xRemainder = DaySum % 32;
else if(DaySum > 16)
xRemainder = DaySum % 16;
else if(DaySum > 8)
xRemainder = DaySum % 8;
else if(DaySum > 4)
xRemainder = DaySum % 4;
else if(DaySum > 2)
xRemainder = DaySum % 2;
else if(DaySum > 1)
xRemainder = DaySum % 1;
return xRemainder;
}
private string SelectedDay(int SumValue)
{
if((SumValue/64) > 0)
return "Saturday";
else if((SumValue/32) > 0)
return "Friday";
else if((SumValue/16) > 0)
return "Thursday";
else if((SumValue/8) > 0)
return "Wednesday";
else if((SumValue/4) > 0)
return "Tuesday";
else if((SumValue/2) > 0)
return "Monday";
else if((SumValue/1) > 0)
return "Sunday";
}
</pre>
有变量来存储值
<pre>
int SumOfDaysSelected = 0;
string DaysSelected = "";
</pre>
然后创建条件以检查根据变量SumOfDaysSelected的值选择的日期或天数
<pre>
while(SumOfDaysSelected > 0)
{
if(DaysSelected == "")
DaysSelected = SelectedDay(SumOfDaysSelected);
else
DaysSelected = DaysSelected + "," + SelectedDay(SumOfDaysSelected);
SumOfDaysSelected = GetRemainder(SumOfDaysSelected);
}
</pre>