2

What is the easiest way to cast an object array to an integer array?

ArrayList al = new ArrayList();
 object arrayObject = al.ToArray(); 
int[]arrayInteger = ?

Thanks

5 Answers 5

8

If you import System.Linq namespace you can do this:

int[] arrayInteger = a1.Cast<int>().ToArray();
Sign up to request clarification or add additional context in comments.

Comments

3

Use int[]arrayInteger = (int[])al.ToArray(typeof(int));

But unless you are using .Net 1.1, user a List<int> instead.

1 Comment

I don't see you converting an object[] here.
2

(object[] eventTypes) Assuming eventTypes are all objects with integer values, this would do it:

        int[] eventTypeIDs = eventTypes.Select( Convert.ToInt32).ToArray();

Comments

1

You could use Array.ConvertAll

int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => (int)o);

One thing to consider is since this is an object array all the values may not be int This is the handy thing about ConvertAll as you can add simple conversion logic to catch errors.

Scenario:

ArrayList al = new ArrayList() { 1,"hello",3,4,5,6 };
int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => { int val = -1; return int.TryParse(o.ToString(), out val) ? val : -1;});

This way we can perform a TryParse on the object to avoid any InvalidCastException due to bad data.

Comments

1

or int[] intArray = object as int[];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.