Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert arraylist to integer array in c#

Tags:

c#

arraylist

This is my code

    con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/techsoft   /PP1.accdb;Persist Security Info=False");
        con.Open();
        cm = new OleDbCommand("select aa from ab", con);
        OleDbDataReader qq;
        qq = cm.ExecuteReader();
        ArrayList ss = new ArrayList();

        while (qq.Read())
        {
            object[] values = new object[qq.FieldCount];
            qq.GetValues(values);
            ss.Add(values);



        }

if i use this syntax to convert

int[] i = (int[])ss.ToArray(System.Type.GetType("System.Int32"));

the following error occurs " At least one element in the source array could not be cast down to the destination array type."

plz suggest me a one solution or any other alternative way

like image 252
ush Avatar asked Sep 10 '26 04:09

ush


2 Answers

If there are objects that are not integers in your ArrayList ss then you need to specify whether to fail or to ignore them.

Assuming you want to ignore them, then you can use LINQ:

int[] res = ss.OfType<int>().ToArray();

(Assuming you have a using System.Linq in scope.)

like image 60
Richard Avatar answered Sep 12 '26 17:09

Richard


Don't use an ArrayList, go for List<int> and you get what you want for free (int array from a list).

If you want to reference the System.Type that represents System.Int32 I'd prefer typeof(int) without string literals and this unnecessary lookup.

The identifiers are hard to read, btw - you might want to make them more easy to understand when you ask a question.

The real problem was identified by the other posters: You add arrays to the list, which aren't integers. Maybe(?) arrays of integers, but we wouldn't know without more details.

like image 33
Benjamin Podszun Avatar answered Sep 12 '26 19:09

Benjamin Podszun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!