How to get the numeric value from a flags enum? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Enums returning int value
How to get the numeric value from the Enum?
THIS IS NOT A DUPLICATE OF EITHER OF THESE, THANKS FOR READING THE QUESTION MODS
Suppose I have a number of my flags enum items selected:
[Flags]
public enum Options
{
None = 0,
Option_A = 1,
Option_B = 2,
Option_C = 4,
Option_D = 8,
}
Options selected = Options.Option_A | Options.Option_B;
The value of selected should correspond to 3 (i.e. 2 + 1)
How can I get this into an int?
I've seen examples where the selected is cast ToString() and then split() into each option, e.g.
"Option_A | Option_B" --> { "Option_A", "Option_B" },
then reconstituted into the respective Enum, and the values taken from that, but it's a bit messy. Is there a more straight-forward way to get the sum of these values?

There is not much options as just make an if
List<int> composedValues = new ....
if((selected & Option_A) == Options.Option_A)
composedValues.Add((int)Options.Option_A);
else if((selected & Option_B) == Options.Option_B)
composedValues.Add((int)Options.Option_B);
else if(...)
Finally you will get a list of all compositional values of the result in the composedValues list.
If this is not what you're asking for, please clarify.

Related

What is enum in worl of OOP? as a custom variable why we use enum? [duplicate]

This question already has answers here:
Get int value from enum in C#
(29 answers)
How do I cast int to enum in C#?
(32 answers)
Closed 1 year ago.
I would like to know more about enums in C#. is it best practice to use enum for creating custom variables? or we can use some another better approach for below example. How we can access it and store enum values to an array of integer using foreach or for loop or any other method.
enum timeSlots
{
AM9h = 0,
AM10h = 1,
AM11h = 2,
AM12h = 3,
PM1h = 4,
PM2h = 5,
PM3h = 6,
PM4h = 7,
PM5h = 8,
PM6h = 9,
}
how can I store timeslots enum's value to an int array?
Well... you can't really. C# is strongly-typed, after all, so any integer array is always going to store integers.
Now what you can do is cast an enum to an int when you want to store it in one of the array elements, and cast it back to the enum type when you need it again. Or you can declare an array of your enum type.
Looks like what you're looking for is Enum.GetValues. Here's an example:
var enums = Enum.GetValues(typeof(timeSlots));
var count = enums.Length;
var array = new int[count];
for(var i = 0; i < count; i++)
array[i] = enums[i];
Not on a computer, so can't test it out right now. Hope it gives you some direction.

Iterating through variable names with for loop [duplicate]

This question already has answers here:
Variables in a loop
(9 answers)
Loop through object variables with different number on the name [duplicate]
(5 answers)
Iteration with variable name [duplicate]
(1 answer)
Closed 2 years ago.
I am trying to use a for loop to iterate through a series of variable names each ending in a number from 1 to 10. I have seen a few other answers to this question but have been unable to make any work for my specific situation. My code is as follows:
string cat2Pos0 = cat2[0];
int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count();
List<int> indexOfPos0 = new List<int>();
bool check = cat2.Contains(cat2Pos0);
int index = 0;
if (check == true)
{
for (int i = 0; i < numOfPos0; i++)
{
index = cat2.FindIndex(x => x == cat2Pos0);
indexOfPos0.Add(cat2.IndexOf(cat2Pos0));
}
}
else if (cat2Pos0 == "-")
{
numOfPos0 = 17;
}
I need to loop through 10 variables names cat1 - cat10. In the code: whenever there is the phrase "cat" I need to be able to adjust it depending on a for loop e.g. cat1 or cat5:
string cat3pos0 = cat3[0];
or:
index = cat3.FindIndex(x => x == cat3Pos0);
Unfortuantely, I am unable to simply write out each variation individually as that would use up almost 3700 lines of code and I was hoping that there would be a better way of achieveing this.
Many thanks, all help is greatly appreciated,
Josh
See here how to use reflection for this. (something like this.GetType().GetField("cat" + i.ToString());.)
But I would really suggest changing your variables to one array of 10 variables. So cat will be an array of arrays (since your cat's seem to be arrays).

List of enums to bit string

I have created a permission enum Flags that controls access:
[Flags]
public enum PermissionEnum
{
None = 0,
Read = 1,
Write = 2,
Delete = 4,
All = 7
}
If someone requests access the different enum values will be added to a list:
List<PermissionEnum> permissions = new List<PermissionEnum> { 1, 4 }
How can I flatten out the list of enums to a bit string?
E.g.
[1,4] = "101"
You're doing it the wrong way. Instead of a list, you should store in a single PermissionEnum variable and for each permission to be added, do a bitwise or:
PermissionEnum pe = PermissionEnum.None; //Current value:0
pe |= PermissionEnum.Read; //Add Read permission. Current value: 1
pe |= PermissionEnum.Delete;//Add Delete permission. Current value: 5
Then you can display the value converting the int to a string:
string result = Convert.ToString((int)pe, 2); //yields "101"
To remove a permission, use bitwise and and bitwise not
pe &= ~PermissionEnum.Read; //Removes Read permission. Current value: 4
Also, to check if some permission is setted, use bitwise and and check if is greater than 0:
bool canRead = (pe & PermissionEnum.Read) > 0;
Step 1
Combine your list of flags into a single enum value:
PermissionEnum combined = permissions.Aggregate(PermissionEnum.None,
(cmb, perm) => cmb | perm);
Step 2
Convert the combined value into a bit string:
string bitString = Convert.ToString((int)combined, 2);
Note that if you can change the interface so you just get the combined enum instead of a list, you can avoid step 1 altogether.

Combine to array sorts into one? [duplicate]

This question already has answers here:
How can I sort a List<T> by multiple T.attributes?
(3 answers)
Closed 4 years ago.
I was wondering if it is possible to combine my sorting code into one ?
I sort my array firstly by enum, then by an id number from lowest to highest.
So my current code looks like this:
_entities = _entities.OrderBy(a => a.Priority).ToArray(); //sort by enum
_entities = _entities.OrderBy(a => a.PriorityID).ToArray(); //then sort by id
So the enum has:
High, Medium,Low
And IDs are just integers.
So the end result should be like:
High¬
0 , 1 ,2
Medium¬
0, 1, 2
Low¬
0, 1, 2
I don't know the syntax to combine these, or if this is as simple as it gets? But it does seem a bit inefficient to be sorting by each property one by one.
Whats the correct way to do ths?
You can use ThenBy:
_entities = _entities.OrderBy(a => a.Priority).ThenBy(a => a.PriorityID).ToArray();

How to know which checkbox are selected if I have a number with the sum of all values checked?

I have an existing database, and my table has a field in which is stored a value, a sum of all "values" of my checkbox list.
Another programmer made this method, called it "logic sum". I don't know this method, but now I need to know the reverse method, so I can know which checkboxes are selected by using the Sum value of all their values.
I really don't know how to do this ... I am using C# with asp.net, but the logic should to be the same for all languages.
Can you help me?
Normally these things are done with powers of 2... The first checkbox has a "weight" of 1, the second one has a "weight" of 2, the third one a "weight" of 4 and so on.
You can check if a checkbox is checked by doing
if ((sum & 1) != 0) // first is checked
if ((sum & 2) != 0) // second is checked
if ((sum & 4) != 0) // third is checked
or
bool firstIsChecked = (sum & 1) != 0;
bool secondIsChecked = (sum & 2) != 0;
bool thirdIsChecked = (sum & 4) != 0;
and so on.
if you don't like binary math, you can go through an enum to leverage the Enum.HasFlag method:
[Flags]
public enum MyChechboxes
{
FooCheckbox = 1,
BarCheckbox = 2,
BazCheckbox = 4,
}
int sum = 5;
MyChechboxes checkeds = (MyChechboxes)sum;
bool firstIsChecked = checkeds.HasFlag(MyChechboxes.FooCheckbox);
bool secondIsChecked = checkeds.HasFlag(MyChechboxes.BarCheckbox);
bool thirdIsChecked = checkeds.HasFlag(MyChechboxes.BazCheckbox);
Let's assume you have a company with 5 features (A,B,C,D,E)
Saving..
if(A.isChecked)
features = features | 1;
if(B.isChecked)
features = features | 2;
if(C.isChecked)
features = features | 4;
if(D.isChecked)
features = features | 8;
if(E.isChecked)
features = features | 16;
Store features value in you db.
Loading..
Get the value off you db
if(features&1)
A is checked
if(features&2)
B is checked
if(features&4)
C is checked
if(features&8)
D is checked
if(features&16)
E is checked
Do you know how to work with flags?
For this logical sum method to be reversible it must use the same principle as flags enums: each possible combination of checkboxes must result in a single unique number.
I'm guessing there are not that many checkboxes, numbered like this:
1, 2, 4, 8, 16, 32... etc. This way any combination will result in a single number, and the logical sum will be reversible.

Categories

Resources