Enum with flags attribute

I have an enumeration:

[Flags, Serializable,] public enum WeekDays { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, WeekendDays = Sunday | Saturday, WorkDays = Monday | Tuesday | Wednesday | Thursday | Friday, EveryDay = WeekendDays | WorkDays } 

And I have a WeekDays property in the class that contains the WeekDays enum value:

 public int WeekDays {get; set;} 

For example, WorkDays contains 62 (Monday through Friday).
How to check that the current WeekDays property contains the current day?

+4
source share
7 answers

Enum has a HasFlag method to determine if one or more bit fields are set in the current instance.

+9
source

Use the bitwise & operator to find out if a value is part of a set:

 var today = WeekDays.Thursday; var workdays = WeekDays.WorkDays; if((today & workdays) == today) { // today is a workday } if((today & WeekDays.Friday) == today) { // it friday } 
+6
source

Use & :

  [Flags, Serializable,] public enum WeekDays { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, WeekendDays = Sunday | Saturday, WorkDays = Monday | Tuesday | Wednesday | Thursday | Friday, EveryDay = WeekendDays | WorkDays } public static WeekDays Days { get; set; } private static void Main(string[] args) { WeekDays today = WeekDays.Sunday; Days = WeekDays.WorkDays; if ((Days & today) == today) { Console.WriteLine("Today is included in Days"); } Console.ReadKey(); } 
+3
source
 WeekDays weekDayValue = .... ; var today = Enum.Parse(typeof(WeekDays),DateTime.Now.DayOfWeek.ToString()) bool matches = ( weekDayValue & today ) == today; 
+3
source

do:

 int r = (int)(WeekDays.WorkDays & WeekDays.Sunday) if (r !=0) you have it. 
+1
source

To do this, you need to use bitwise logic. if you would say

 WeekDays.Tuesday & WeekDays.WorkDays 

then logical logic will return 4 (since 4 & 62 = 4).

Essentially, and says that for each bit position, if both are equal to 1, return that number. So you just need to check if it is> 0.

To get Today in your current format, you will need a little math ...

(int)DateTime.Now.DayOfWeek will return the day of the week from 0 (Sunday) to 6 (Saturday).

We need to match them to fit your range. Fortunately, this is easy to do with Math.Pow.

 int today = Math.Pow(2,(int)DateTime.Now.DayOfWeek); if (today&WeekDays.WorkDays>0) isWorkDay = true; else isWorkDay = false; 
+1
source

Get all the names and values โ€‹โ€‹of the enumeration, then do an "and" to check if WeekDays contains the current day

0
source

Source: https://habr.com/ru/post/1398008/


All Articles