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
}
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.
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);
If I have two lists of type string (or any other type), what is a quick way of joining the two lists?
The order should stay the same. Duplicates should be removed (though every item in both links are unique). I didn't find much on this when googling and didn't want to implement any .NET interfaces for speed of delivery.
You could try:
List<string> a = new List<string>();
List<string> b = new List<string>();
a.AddRange(b);
MSDN page for AddRange
This preserves the order of the lists, but it doesn't remove any duplicates (which Union would do).
This does change list a. If you wanted to preserve the original lists then you should use Concat (as pointed out in the other answers):
var newList = a.Concat(b);
This returns an IEnumerable as long as a is not null.
The way with the least space overhead is to use the Concat extension method.
var combined = list1.Concat(list2);
It creates an instance of IEnumerable<T> which will enumerate the elements of list1 and list2 in that order.
The Union method might address your needs. You didn't specify whether order or duplicates was important.
Take two IEnumerables and perform a union as seen here:
int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };
IEnumerable<int> union = ints1.Union(ints2);
// yields { 5, 3, 9, 7, 8, 6, 4, 1, 0 }
Something like this:
firstList.AddRange (secondList);
Or, you can use the 'Union' extension method that is defined in System.Linq.
With 'Union', you can also specify a comparer, which can be used to specify whether an item should be unioned or not.
Like this:
List<int> one = new List<int> { 1, 2, 3, 4, 5 };
List<int> second=new List<int> { 1, 2, 5, 6 };
var result = one.Union (second, new EqComparer ());
foreach( int x in result )
{
Console.WriteLine (x);
}
Console.ReadLine ();
#region IEqualityComparer<int> Members
public class EqComparer : IEqualityComparer<int>
{
public bool Equals( int x, int y )
{
return x == y;
}
public int GetHashCode( int obj )
{
return obj.GetHashCode ();
}
}
#endregion
targetList = list1.Concat(list2).ToList();
It's working fine I think so. As previously said, Concat returns a new sequence and while converting the result to List, it does the job perfectly. Implicit conversions may fail sometimes when using the AddRange method.
If some item(s) exist in both lists you may use
var all = list1.Concat(list2).Concat(list3) ... Concat(listN).Distinct().ToList();
As long as they are of the same type, it's very simple with AddRange:
list2.AddRange(list1);
var bigList = new List<int> { 1, 2, 3 }
.Concat(new List<int> { 4, 5, 6 })
.ToList(); /// yields { 1, 2, 3, 4, 5, 6 }
The AddRange method
aList.AddRange( anotherList );
List<string> list1 = new List<string>();
list1.Add("dot");
list1.Add("net");
List<string> list2 = new List<string>();
list2.Add("pearls");
list2.Add("!");
var result = list1.Concat(list2);
one way: List.AddRange() depending on the types?
One way, I haven't seen mentioned that can be a bit more robust, particularly if you wanted to alter each element in some way (e.g. you wanted to .Trim() all of the elements.
List<string> a = new List<string>();
List<string> b = new List<string>();
// ...
b.ForEach(x=>a.Add(x.Trim()));
See this link
public class ProductA
{
public string Name { get; set; }
public int Code { get; set; }
}
public class ProductComparer : IEqualityComparer<ProductA>
{
public bool Equals(ProductA x, ProductA y)
{
//Check whether the objects are the same object.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether the products' properties are equal.
return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
}
public int GetHashCode(ProductA obj)
{
//Get hash code for the Name field if it is not null.
int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = obj.Code.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 },
new ProductA { Name = "orange", Code = 4 } };
ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 },
new ProductA { Name = "lemon", Code = 12 } };
//Get the products from the both arrays
//excluding duplicates.
IEnumerable<ProductA> union =
store1.Union(store2);
foreach (var product in union)
Console.WriteLine(product.Name + " " + product.Code);
/*
This code produces the following output:
apple 9
orange 4
lemon 12
*/
The two options I use are:
list1.AddRange(list2);
or
list1.Concat(list2);
However I noticed as I used that when using the AddRange method with a recursive function, that calls itself very often I got an SystemOutOfMemoryException because the maximum number of dimensions was reached.
(Message Google Translated)
The array dimensions exceeded the supported range.
Using Concat solved that issue.
I just wanted to test how Union works with the default comparer on overlapping collections of reference type objects.
My object is:
class MyInt
{
public int val;
public override string ToString()
{
return val.ToString();
}
}
My test code is:
MyInt[] myInts1 = new MyInt[10];
MyInt[] myInts2 = new MyInt[10];
int overlapFrom = 4;
Console.WriteLine("overlapFrom: {0}", overlapFrom);
Action<IEnumerable<MyInt>, string> printMyInts = (myInts, myIntsName) => Console.WriteLine("{2} ({0}): {1}", myInts.Count(), string.Join(" ", myInts), myIntsName);
for (int i = 0; i < myInts1.Length; i++)
myInts1[i] = new MyInt { val = i };
printMyInts(myInts1, nameof(myInts1));
int j = 0;
for (; j + overlapFrom < myInts1.Length; j++)
myInts2[j] = myInts1[j + overlapFrom];
for (; j < myInts2.Length; j++)
myInts2[j] = new MyInt { val = j + overlapFrom };
printMyInts(myInts2, nameof(myInts2));
IEnumerable<MyInt> myUnion = myInts1.Union(myInts2);
printMyInts(myUnion, nameof(myUnion));
for (int i = 0; i < myInts2.Length; i++)
myInts2[i].val += 10;
printMyInts(myInts2, nameof(myInts2));
printMyInts(myUnion, nameof(myUnion));
for (int i = 0; i < myInts1.Length; i++)
myInts1[i].val = i;
printMyInts(myInts1, nameof(myInts1));
printMyInts(myUnion, nameof(myUnion));
The output is:
overlapFrom: 4
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myInts2 (10): 4 5 6 7 8 9 10 11 12 13
myUnion (14): 0 1 2 3 4 5 6 7 8 9 10 11 12 13
myInts2 (10): 14 15 16 17 18 19 20 21 22 23
myUnion (14): 0 1 2 3 14 15 16 17 18 19 20 21 22 23
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myUnion (14): 0 1 2 3 4 5 6 7 8 9 20 21 22 23
So, everything works fine.