I need to get the numeric position of an enum in its definition.
Consider the following enum - it is used for bit fields but the status names
would be useful if they had the values on the right that I have commented.
[Flags]
public enum StatusFlags
{
None = 0, // 0 -- these commented indexes are the numbers I also would like
Untested = 1, // 1 to associate with the enum names.
Passed_Programming = 2, // 2
Failed_Programming = 4, // 3
// ... many more
}
I have created a static method as follows, which works for what I want.
public static int GetStatusID(this StatusFlags flag)
{
int i = 0;
foreach (StatusFlags val in Enum.GetValues(typeof(StatusFlags)))
{
if (flag == val) break;
i++;
}
return i;
}
It is used like this:
StatusFlags f = StatusFlags.Failed_Programming;
// I want the position i.e value of 3 not the value the enum is associated with i.e 4
int Index = f.GetStatusID();
Is there is a better way to do this?
How about using attributes on your enum? Something like this:
[Flags]
public enum StatusFlags
{
[Index=0]
None = 0,
[Index=1]
Untested = 1,
[Index=2]
Passed_Programming = 2,
[Index=3]
Failed_Programming = 4,
// ... many more
}
Then you can the index value of your enum like this:
var type = typeof(StatusFlags);
var statusFlag = type.GetMember(StatusFlags.Untested.ToString());
var attributes = statusFlag [0].GetCustomAttributes(typeof(IndexAttribute),false);
var index = int.Parse(((IndexAttribute)attributes[0]).Index); //if you need an int value
A deleted answer here suggested something that resembled
public static int GetStatusID(this StatusFlags flag)
{
return Array.IndexOf(Enum.GetValues(typeof(StatusFlags)), flag);
}
and was just missing the syntactical point that IndexOf is a static function in the Array class, not an extension method. I like it though for brevity.
You could do this:
public static int GetStatusID(this StatusFlags flag)
{
return
Enum
.GetValues(typeof(StatusFlags))
.Cast<StatusFlags>()
.Select((f, n) => new { f, n })
.Where(fn => fn.f == flag)
.Select(fn => fn.n)
.DefaultIfEmpty(0)
.First();
}
How about just using math? He says the flags go up in powers of 2
int GetStatusID(this StatusFlags flag)
{
if (((int)flag) == 0) return 0;
return (Math.Log((double)flag) / Math.Log(2D)) + 1;
}
If each flag has only 1 bit set like that then the index is just Math.Log2((int)flag) + 1. However Math.Log2 is a floating-point operation and is very slow so don't use it
If you're using .NET Core then there are BitOperations.Log2 and BitOperations.TrailingZeroCount which map directly to hardware instructions like TZCNT/BSF in x86 or CLZ in ARM, hence are much more efficient and the result is like this
public static int GetStatusID(this StatusFlags flag)
{
if ((int)flag == 0)
return 0;
return BitOperations.Log2((int)flag);
// or return BitOperations.TrailingZeroCount((int)flag) + 1;
}
If you're using an older .NET framework then calculate see the way to calculate integer log2 quickly in these questions
What's the quickest way to compute log2 of an integer in C#?
Fastest implementation of log2(int) and log2(float)
Fast way of finding most and least significant bit set in a 64-bit integer
Related
Example, I have a random number, but it can have "special numbers" values. Something like that:
enum XNumber { INFINITY, NEGATIVE, int }
So I could store:
var i = XNumber.INFINITY;
var i = XNumber.NEGATIVE;
var i = (XNumber) 1;
var i = (XNumber) 500;
var i = (XNumber) -1000;
If not, what are my possibilities to do that?
An enum can be cast to/from an int provided the values match up. Note that you can assign numeric values to enum values. For instance,
namespace Test
{
enum SpecialValue
{
Zero = 0,
Five = 5,
Seventy = 70
}
private void method()
{
var five = (SpecialValue)5; // == SpecialValue.Five
int seventy = (int)SpecialValue.Seventy; // == 70
}
}
The easiest way is probably putting both the int and the enum into a struct. You can define conversion operators and arithmetic operators to make working with your type easier.
e.g.
struct XNumber {
private enum SpecialValue { Normal, Negative, Infinity}
private int value;
private SpecialValue kind;
public XNumber Infinity = new XNumber { kind = SpecialValue.Infinity };
public XNumber Negative = new XNumber { kind = SpecialValue.Negative };
public static implicit operator XNumber(int value) {
if (value < 0)
return new XNumber { kind = SpecialValue.Negative };
return new XNumber { value = value };
}
// ...
}
Something like that, depending on your exact needs.
Another way, if you don't need the full range of int, is to use special values for infinity and negative and you only need to store the int. Still a struct, you should still define conversions and operators so that everything matches up. While you can get away with just an enum, as Wai Ha Lee notes, I'd not recommend it, as you essentially have an own type that has its own semantics (just that those happen to be somewhat supported by enums in C#).
I'm having difficulties working with some legacy enums that have multiple zero values. Whenever I call ToString on one of the non-zero values, all but the first zero value is included.
Is there any way to isolate the non-zero value name without resorting to string manipulation or reflection?
//all of the following output "Nada, Zilch, One"
Console.WriteLine(TestEnum.One);
Console.WriteLine(Convert.ToString(TestEnum.One));
Console.WriteLine(TypeDescriptor.GetConverter(typeof(TestEnum))
.ConvertToString(TestEnum.One));
[Flags]
enum TestEnum
{
Zero = 0,
Nada = 0,
Zilch = 0,
One = 1
}
Edit
I understand that having multiple items with the same value is not recommended however the enum in question is defined in a legacy assembly that I can't change. In fact, there are 12 public enums in mscorlib v4 that break this recommendation, as determined by the following simple LINQ query:
var types = typeof (void).Assembly.GetTypes()
.Where(type => type.IsEnum &&
type.IsPublic &&
Enum.GetValues(type).Cast<object>()
.GroupBy(value => value)
.Any(grp => grp.Count() > 1))
.ToList();
Here is one option. It works, but it's a bit ugly. The values / names variables won't change, so they only need to be calculated once.
Assuming you have a slightly more complicated enum, such as:
[Flags]
public enum TestEnum
{
Zero = 0,
Nada = 0,
Zilch = 0,
One = 1,
Two = 2,
Three = 3,
Four = 4
}
Here is some code you could use:
var input = TestEnum.One | TestEnum.Two;
var values = (TestEnum[]) Enum.GetValues(typeof (TestEnum));
var names = Enum.GetNames(typeof (TestEnum));
var result = values
.Select((value, index) =>
input == value || (value != 0 && (input & value) == value)
? names[index]
: null)
.Where(name => name != null);
var text = string.Join(", ", result);
Console.WriteLine(text);
Alright, first Microsoft recommends against this strongly. Some of the stronger words I've heard them use for something they don't enforce on compile:
Avoid setting a flags enumeration value to zero, unless the value is used to indicate that all flags are cleared. Such a value should be named appropriately as described in the next guideline... Do name the zero value of flags enumerations None. For a flags enumeration, the value must always mean all flags are cleared.
Ok, so why is this happening? From this question I take it's Enum.ToString behaving strangely:
If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return.
EDIT: I'm able to reproduce your results, but I can't find any more documentation on why it would start printing out the other 0 values. I would expect it to print NONE of them.
Can you just right-click->refactor->rename them all the same and then delete the others? It seems easier and less against what Microsoft recommends.
Assuming you have a slightly more complex enum, such as:
[Flags]
public enum TestEnum
{
Zero = 0,
Nada = 0,
Zilch = 0,
One = 1,
Two = 2,
Four = 4,
}
You could implement a simple method that returns the string value for you, like this:
public static string TestEnumToString(TestEnum value)
{
var result = new List();
if (value == TestEnum.Zero)
{
result.Add("Zero");
}
if (value == TestEnum.Nada)
{
result.Add("Nada");
}
if (value == TestEnum.Zilch)
{
result.Add("Zilch");
}
if ((value & TestEnum.One) != 0)
{
result.Add("One");
}
if ((value & TestEnum.Two) != 0)
{
result.Add("Two");
}
if ((value & TestEnum.Four) != 0)
{
result.Add("Four");
}
return string.Join(",", result);
}
I have a property in my class that can only be one of several values, what is the best way to limit the input on this property.
Here is what I'm doing now, and I'm sure there must be a better way.
public void SetValue(int value)
{
if(value != 1 ||
value != 4 ||
value != 8 ||
value != 16 ||
value != 32 ||
value != 64, ||
value != 128)
{
property_value = 1;
}
else
{
property_value = value;
}
}
Instead of in int, use an Enum with these values.
I am sure each value has a specific meaning - expose these as enum members.
This may not eliminate all issues (since an Enum is simply a wrapper over an integer type and can still get assigned a value that doesn't exist in the enumeration), but should take care of most problems, so long as you are consistent about only passing values from the enumeration itself.
In any rate, you can then simply test the passed in value against the enumeration and throw an exception if it isn't a valid member.
Use enum instead of this numeric values like:
enum Numbers { Name1 = 1, Name2 = 4 ... }
and then you can easilly check if value is one of enum element:
Enum.IsDefined(typeof(Numbers), value );
For your example, you can just do:
property_value = 1;
since your if condition will always be true.
If you want to restrict it to a number of possibilities you could:
Declare an enum:
public enum Value
{
Default = 1,
Option1 = 4,
...
}
or have a collection of valid values to check:
int[] validValues = new int[] { 1, 4, 8, 16, 32, 64, 128 };
property_value = validValues.Contains(value) ? value : 1;
Although I would prefer to throw an exception on invalid input.
I think you should consider using an enum:
public enum MyEnum
{
These,
Are,
Valid,
Values
}
public void SetValue(MyEnum _value)
{
// Only MyEnum values allowed here!
}
if(((value & (value − 1)) == 0) && value != 2 && value <= 128)
property_value = 1;
else
property_value = value;
(value & (value − 1)) is a fast way to check if value is a power of two.
As an example: value = 4:
(4(10) & (3(10)) =
100(2) & 011(2) =
000(2) = 0
value = 5
(5(10) & (4(10)) =
101(2) & 100(2) =
100(2) =
4
You could use an enum and check using Enum.IsDefined(value). But then you'd have to think of a (meaningfull) name for all the possible values.
I think we're missing the INTENT of the function here.
It looks like a bit mask check to me. If that's the case, he's missing 2 from the code sample. Also, note that he's not discarding a value if it isn't one of those specific bits: he preserves it. If it is a value equal to a specific bit (and only that bit) he coerces it to 1.
I think the sample provided by Lee works best in this case; it's simple and to the point. Also, if the check is widened to account for 16 bits (or even 32), it will easily catch them all.
I want to check that some integer type belongs to (an) enumeration member.
For Example,
public enum Enum1
{
member1 = 4,
member2 = 5,
member3 = 9,
member4 = 0
}
Enum1 e1 = (Enum1)4 gives me member1
Enum1 e2 = (Enum1)10 gives me nothing and I want to check it.
Use Enum.IsDefined
Enum.IsDefined(typeof(Enum1), 4) == true
but
Enum.IsDefined(typeof(Enum1), 1) == false
As Sam says, you can use IsDefined. This is somewhat awkward though. You may want to look at my Unconstrained Melody library which would let you us:
Enum1 e2 = (Enum1)10;
if (e2.IsNamedValue()) // Will return false
{
}
It's probably not worth it for a single enum call, but if you're doing a lot of stuff with enums you may find some useful things in there.
It should be quicker than Enum.IsDefined btw. It only does a linear scan at the moment, but let me know if you need that to be improved :) (Most enums are small enough that they probably wouldn't benefit from a HashSet, but we could do a binary search...)
int testNum = 5;
bool isMember = Enum.GetValues(typeof(Enum1)).Cast<int>().Any(x => x == testNum);
You look through the values of the enum and compare them to the integer.
static bool EnumTest(int testVal, Enum e)
{
bool result = false;
foreach (var val in Enum.GetValues(typeof(Enum1)))
{
if ((int)val == testVal)
{
result = true;
break;
}
}
return result;
}
Edit: Looks like Sam has a better solution.
You can use Enum.GetValues to get all defined values. Then check if your value exists in that list.
http://msdn.microsoft.com/en-us/library/system.enum.getvalues.aspx
Be careful this won't work if you have an enum for 3 (Apples and Pears) the methods above won't detect it as valid.
[Flags]
public enum Fruit
{
Apples=1,
Pears=2,
Oranges =4,
}
Here's a succinct little snippet from an extension method I wrote a few years ago. Combines TryParse with IsDefined to do it all in one swoop and handle values that don't exist in the enum.
if (value != null)
{
TEnum result;
if (Enum.TryParse(value.ToString(), true, out result))
{
// since an out-of-range int can be cast to TEnum, double-check that result is valid
if (Enum.IsDefined(typeof(TEnum), result.ToString() ?? string.Empty))
{
return result;
}
}
}
Here's the extension for integer values
public static TEnum ParseToEnum<TEnum>(this int value, TEnum? defaultValue = null, bool useEnumDefault = false) where TEnum : struct
{
return ParseToEnumInternal(value, defaultValue, useEnumDefault);
}
And a usage
public enum Test
{
Value1 = 1,
Value2 = 3
}
var intValue = 1;
var enumParsed = intValue.ParseToEnum<Test>(); // converts to Test.Value1
intValue = 2;
enumParsed = intValue.ParseToEnum<Test>(); // either throws or converts to supplied default
enumParsed = 3.ParseToEnum<Test>(); // converts to Test.Value2
Some people don't like how it dangles off the end of the (potentially nullable) value, but I have an extension that handles null values of nullable types (int?) and I like it myself, so ...
I can post like a Gist of the whole extension method with all the overloads if you're interested.
Use:
if (Enum.IsDefined(typeof(Fruit),e2))
{
//Valid Value
}
else
{
//Invalid ENum Value
}
Found this useful. https://stackoverflow.com/a/64374930/16803533
no need to use IsDefined and No range checking
What is the best algorithm to take array like below:
A {0,1,2,3}
I expected to order it like array below:
B {3,1,0,2}
Any ideas?
So if you have two arrays and they hold the same data just in different order then just do this:
A = B
I suspect that is not your situation so I think we need more info.
What you need to do is determine the ordering of B and then apply that ordering to A. One way to accomplish this is to undo the ordering of B and keep track of what happens along the way. Then you can do the reverse to A.
Here's some sketchy C# (sorry, I haven't actually run this)...
Take a copy of B:
List<int> B2 = new List<int>(B);
Now sort it, using a sort function that records the swaps:
List<KeyValuePair<int,int>> swaps = new List<KeyValuePair<int,int>>();
B2.Sort( delegate( int x, int y ) {
if( x<y ) return -1;
if( x==y ) return 0;
// x and y must be transposed, so assume they will be:
swaps.Add( new KeyValuePair<int,int>(x,y) );
return 1;
});
Now apply the swaps, in reverse order, to A:
swaps.Reverse();
foreach( KeyValuePair<int,int> x in swaps )
{
int t = A[x.key];
A[x.key] = A[x.value];
A[x.value] = t;
}
Depending how the built-in sort algorithm works, you might need to roll your own. Something nondestructive like a merge sort should give you the correct results.
Here's my implementation of the comparer (uses LINQ, but can be easily adapted to older .net versions). You can use it for any sorting algorithms such as Array.Sort, Enumerable.OrderBy, List.Sort, etc.
var data = new[] { 1, 2, 3, 4, 5 };
var customOrder = new[] { 2, 1 };
Array.Sort(data, new CustomOrderComparer<int>(customOrder));
foreach (var v in data)
Console.Write("{0},", v);
The result is 2,1,3,4,5, - any items not listed in the customOrder are placed at the end in the default for the given type (unless a fallback comparator is given)
public class CustomOrderComparer<TValue> : IComparer<TValue>
{
private readonly IComparer<TValue> _fallbackComparer;
private const int UseDictionaryWhenBigger = 64; // todo - adjust
private readonly IList<TValue> _customOrder;
private readonly Dictionary<TValue, uint> _customOrderDict;
public CustomOrderComparer(IList<TValue> customOrder, IComparer<TValue> fallbackComparer = null)
{
if (customOrder == null) throw new ArgumentNullException("customOrder");
_fallbackComparer = fallbackComparer ?? Comparer<TValue>.Default;
if (UseDictionaryWhenBigger < customOrder.Count)
{
_customOrderDict = new Dictionary<TValue, uint>(customOrder.Count);
for (int i = 0; i < customOrder.Count; i++)
_customOrderDict.Add(customOrder[i], (uint) i);
}
else
_customOrder = customOrder;
}
#region IComparer<TValue> Members
public int Compare(TValue x, TValue y)
{
uint indX, indY;
if (_customOrderDict != null)
{
if (!_customOrderDict.TryGetValue(x, out indX)) indX = uint.MaxValue;
if (!_customOrderDict.TryGetValue(y, out indY)) indY = uint.MaxValue;
}
else
{
// (uint)-1 == uint.MaxValue
indX = (uint) _customOrder.IndexOf(x);
indY = (uint) _customOrder.IndexOf(y);
}
if (indX == uint.MaxValue && indY == uint.MaxValue)
return _fallbackComparer.Compare(x, y);
return indX.CompareTo(indY);
}
#endregion
}
In the example you gave (an array of numbers), there would be no point in re-ordering A, since you could just use B.
So, presumably these are arrays of objects which you want ordered by one of their properties.
Then, you will need a way to look up items in A based on the property in question (like a hashtable). Then you can iterate B (which is in the desired sequence), and operate on the corresponding element in A.
Both array's contain the same values (or nearly so) but I need to force them to be in the same order. For example, in array A the value "3045" is in index position 4 and in array B it is in index position 1. I want to reorder B so that the index positions of like values are the same as A.
If they are nearly the same then here is some pseudo code:
Make an ArrayList
Copy the contents of the smaller array to the arraylist
for each item I in the larger array
FInd I in the ArrayList
Append I to a new array
Remove I from the arraylist
Could the issue be resolved using a Dictionary so the elements have a relationship that isn't predicated on sort order at all?