tags:

views:

1182

answers:

2

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

+8  A: 

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);
Marc Gravell
+1 Beat me to it with int[] result = Array.ConvertAll(enumArray, value => (int) value);
johnc
Very nice! Just used in code and works like a charm, nice to no have to individually convert the long list. Thanks!
rball
+1  A: 

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.

Jay Bazuzi