I have two enums and I want to determine from user input(string), in which array is the enum with the same name from user input
public enum LengthUnit
{
mm = -3,
cm = -2,
dm = -1,
m = 0,
km = 3
}
public enum NumericUnit
{
b = 2,
o = 8,
d = 10,
h = 16
}
string input = "cm";
Sounds like you want Enum.TryParse which will let you pass a string and the enum type as parameters and an out parameter as the result if the TryParse succeeds.
Related
Consider the following Enum:
[Flags]
public enum Digit:
UInt64
{
None = 00 << 00,
One = 01 << 00,
Two = 01 << 01,
Three = 01 << 02,
// Etcetera...
Other = UInt64.MaxValue - 1,
Unknown = UInt64.MaxValue,
}
var type = typeof(Digit);
// Returns System.String [].
var names = Enum.GetNames(type);
// Returns System.Array.
var values = Enum.GetValues(type);
// Returns IEnumerable<object>.
var values = Enum.GetValues(type).Cast<object>();
Now, I want to get the numeric value of the Enum members without having to cast them to a specific integral type. This is for code generation purposes so below is an example of the code I want to be able to generate:
[Flags]
public enum Digit:
UInt64
{
None = 0,
One = 1,
Two = 2,
Three = 4,
// Etcetera...
Other = 18446744073709551614,
Unknown = 18446744073709551615,
}
Of course, I could check the underlying type of the enumeration by calling Enum.GetUnderlyingType(type); and use conditional code to cast each case but was wondering if there is a more direct way.
Please note that I am just looking for the textual representation of the integral value and do not need to do any arithmetic with it or manipulation on it.
Am I missing something simple or is there no way to achieve this without casting?
I don't think there's a way to do this without some kind of conversion, but you can do it without having to use conditional code.
For example:
using System;
using System.Linq;
static class Program
{
[Flags]
public enum Digit :
UInt64
{
None = 00 << 00,
One = 01 << 00,
Two = 01 << 01,
Three = 01 << 02,
// Etcetera...
Other = UInt64.MaxValue - 1,
Unknown = UInt64.MaxValue,
}
public static void Main()
{
var type = typeof(Digit);
var values = Enum.GetValues(type);
var underlyingType = Enum.GetUnderlyingType(type);
var strings =
values.Cast<object>()
.Select(item => Convert.ChangeType(item, underlyingType).ToString())
.ToArray();
Console.WriteLine(string.Join(", ", strings));
}
}
This outputs: 0, 1, 2, 4, 18446744073709551614, 18446744073709551615
my enum :
public enum UNH
{
Message_Reference_Identifier = 0,
Message_Type = 1,
Message_version_number = 2,
Message_release_number = 3,
Controlling_agency = 4,
Association_assigned_code = 5
}
my code line :
int tagcount = Enum.GetNames(typeof(UNH)).Length;
My question is how can I pass UNH as a parameter to typeof(), where UNH will be stored in a string variable.
Hello all, I have multiple enums let's say ABC, DEF, GHI. I would be receiving a string as input parameter, the string would be something like this "ABC+anythinghere", "DEF+anythinghere" and so on. So from here depending on first 3 characters of string parameter i.e. ABC, DEF.... I need to call enum properties which are of same name.
Example if first 3 chars are ABC then there would be n enum values for it similarly if first 3 chars are DEF then there would be m enum values for it.
This first 3 chars would be retrieved from the input string parameter in the form of string let's say testname, when passing the string name into typeof() like typeof(testname) it would obviously consider the variable as string which is not required instead I need a way where the value of testname i.e ABC, DEF.... would be passed into typeof()
Maybe I misunderstood the question, but this may help:
Enum.GetName:
public class Example
{
public enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
public static void Main()
{
int value = 5;
string day = Enum.GetName(typeof(Days), value);
Console.WriteLine(day);
}
}
// Output: Friday
Using casting:
public class Example
{
public enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
public static void Main()
{
int value = 5;
var day = (Days)value;
Console.WriteLine(day);
}
}
/*
Output: Friday
*/
Hope this help you to solve a problem you got!
CompBitsList companyBit;
public CompBitsList CompanyBit { get => companyBit; set => companyBit= value; }
[Flags]
public enum CompBitsList
{
None = 0
BitOption1 = 1,
BitOption2 = 2,
BitOption3 = 4,
BitOption4 = 8,
BitOption5 = 16,
BitOption6 = 32,
}
Lets say I have the integer value 22 that would contain the enum flags BitOption2, BitOption3 and BitOption5 (2+4+16). Is there a way to automate this so that I can pass the integer value and have the enum variable CompanyBit set automatically?
companyBit = CompBitsList.BitOption2 | CompBitsList.BitOption3 | CompBitsList.BitOption5
I'm not very familar with enums but I would prefer not to do the method above so any suggestions are appreciated. Thanks :)
You can just cast the int to an instance of CompBitsList.
CompBitsList companyBit = (CompBitsList)22;
companyBit.HasFlag(CompBitsList.BitOption2); // True
companyBit.HasFlag(CompBitsList.BitOption3); // True
companyBit.HasFlag(CompBitsList.BitOption5); // True
companyBit.HasFlag(CompBitsList.BitOption6); // False
You can also define a value on that enum that represents a combination of flags, if it makes sense and you'll be combining those flags a lot.
[Flags]
public enum CompBitsList
{
None = 0
BitOption1 = 1,
BitOption2 = 2,
BitOption3 = 4,
BitOption4 = 8,
BitOption5 = 16,
BitOption6 = 32,
BitOptions2And3And5 = BitOption2 | BitOption3 | BitOption5 //or just 22
}
This question already has answers here:
HasFlag always returns True
(5 answers)
Closed 4 years ago.
I have a Enum with Flags like this:
[Flags]
public enum ItemType
{
Shop,
Farm,
Weapon,
Process,
Sale
}
Then I have several objects in a list with some flags set and some flags not set. It looks like this:
public static List<ItemInfo> AllItems = new List<ItemInfo>
{
new ItemInfo{ID = 1, ItemType = ItemType.Shop, Name = "Wasserflasche", usable = true, Thirst = 50, Hunger = 0, Weight = 0.50m, SalesPrice = 2.50m, PurchasePrice = 5, ItemUseAnimation = new Animation("Trinken", "amb#world_human_drinking#coffee#female#idle_a", "idle_a", (AnimationFlags.OnlyAnimateUpperBody | AnimationFlags.AllowPlayerControl)) },
new ItemInfo{ID = 2, ItemType = ItemType.Sale, Name = "Sandwich", usable = true, Thirst = 0, Hunger = 50, Weight = 0.5m, PurchasePrice = 10, SalesPrice = 5, ItemUseAnimation = new Animation("Essen", "mp_player_inteat#pnq", "intro", 0) },
new ItemInfo{ID = 3, ItemType = (ItemType.Shop|ItemType.Process), Name = "Apfel", FarmType = FarmTypes.Apfel, usable = true, Thirst = 25, Hunger = 25, Weight = 0.5m, PurchasePrice = 5, SalesPrice = 2, ItemFarmAnimation = new Animation("Apfel", "amb#prop_human_movie_bulb#base","base", AnimationFlags.Loop)},
new ItemInfo{ID = 4, ItemType = ItemType.Process, Name = "Brötchen", usable = true, Thirst = -10, Hunger = 40, Weight = 0.5m, PurchasePrice = 7.50m, SalesPrice = 4}
}
Then I go trough the list with a loop and ask if the flag ItemType.Shop is set or not, like this:
List<ItemInfo> allShopItems = ItemInfo.AllItems.ToList();
foreach(ItemInfo i in allShopItems)
{
if (i.ItemType.HasFlag(ItemType.Shop))
{
API.consoleOutput(i.Name);
}
}
This is the output of my loop - it shows all items in the list, and the .HasFlag method always returns true in this case.
Wasserflasche
Sandwich
Apfel
Brötchen
Try to assign values to your enum
[Flags]
public enum ItemType
{
Shop = 1,
Farm = 2,
Weapon = 4,
Process = 8,
Sale = 16
}
Here are some Guidelines for FlagsAttribute and Enum (excerpt from Microsoft Docs)
Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.
Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
You should assign values to your enums. All the flags attribute does is change how the ToString method works. I would use a bitwise operator to make it less likely to make a mistake:
[Flags]
public enum ItemType
{
Shop = 1 << 0, // == 1
Farm = 1 << 1, // == 2
Weapon = 1 << 2, // == 4
Process = 1 << 3, // == 8
Sale = 1 << 4 // == 16
}
I have this flag enum:
public enum DataAccessPoliceis
{
None = 0,
A = 1,
B = 2,
C = 4,
D = 8,
E = B | C | D, // 14
All = A | E // 15
}
I want to get int value (or list of int values for complex enum item) from int value:
int x = 9; // enum items => D | A
List<int> lstEnumValues = ???
// after this line ...
// lstEnumValues = { 1, 8 }
// and for x = 15
// lstEnumValues = { 1, 2, 4, 8, 14, 15 }
What's your solution for this question?
Use can use the class Enum and the GetValues method. Try it Like this:
var lstEnumValues = new List<int>(Enum.GetValues(typeof(DataAccessPolicies)).Cast<int>());
The output is:
Hope this helps.
Answer of my question:
var lstEnumValues = new List<int>Enum.GetValues(typeof(DataAccessPoliceis)).Cast<int>())
.Where(enumValue => enumValue != 0 && (enumValue & x) == enumValue).ToList();
#dyatchenko and #Enigmativity thank you for your responses.
Try:
var lstEnumValues =
((DataAccessPoliceis[])(Enum.GetValues(typeof(DataAccessPoliceis))))
.Where(v => v.HasFlag(x))
.Select(v => (int)v) // omit if enum values are OK
.ToList(); // omit if List<> not needed
For these scenarios I prefer using extension methods.
public static IEnumerable<Enum> ToEnumerable(this Enum input)
{
foreach (Enum value in Enum.GetValues(input.GetType()))
if (input.HasFlag(value) && Convert.ToInt64(value) != 0)
yield return value;
}
Usage:
var lstEnumValues = flagEnum.ToEnumerable().Select(x => Convert.ToInt32(x)).ToList();
Yet another approach:
As flags are only combinations of exponentiated numbers to base 2 and every natural number has exactly one representation in the binary number-system, it is actually sufficient to consider only the binary representation (not the enum itself). After the conversion to the binary representation, there is only to convert all places with a "1" back to the decimal-system (and to omit the zeros) and to output in form of a list.
With a little help from LINQ this can be written like this:
int value = 9;
//convert int into a string of the the binary representation
string binary = Convert.ToString(value, 2);
var listOfInts = binary
//convert each binary digit back to a decimal
.Select((v, i) => Int32.Parse(v.ToString()) * Math.Pow(2, binary.Length-i-1))
//filter decimal numbers that are based on the "1" in binary representation
.Where(x => x > 0)
//you want the integers in ascending order
.OrderBy(x => x);