Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array of 'enum' to an array of 'int'

Tags:

c#

.net

I'm trying to convert an Enum array to an int array:

public enum TestEnum { Item1, Item2 }  int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(Convert.ToInt32)); 

For some reason Convert.ToInt32 doesn't work when used in Array.ConvertAll, so I had to make some changes:

int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(ConvertTestEnumToInt));  public static int ConvertTestEnumToInt(TestEnum te) { return (int)te; } 

Just out of curiosity, is there any way to have this working without using an extra method?

Regards

like image 939
Waleed Eissa Avatar asked Jan 23 '09 09:01

Waleed Eissa


2 Answers

Just cast using an anonymous method:

int[] result = Array.ConvertAll<TestEnum, int>(     enumArray, delegate(TestEnum value) {return (int) value;}); 

or with C# 3.0, a lambda:

int[] result = Array.ConvertAll(enumArray, value => (int) value); 
like image 137
Marc Gravell Avatar answered Sep 22 '22 01:09

Marc Gravell


Luckily for us, C# 3.0 includes a Cast operation:

int[] result = enumArray.Cast<int>().ToArray(); 

If you stop using arrays and start using IEnumerable<>, you can even get rid of the ToArray() call.

like image 29
Jay Bazuzi Avatar answered Sep 21 '22 01:09

Jay Bazuzi