ArrayList to int[] in c#
I have my declaration as follows
int[] EmpIDs = new int[] { };
ArrayList arrEmpID = new ArrayList();
int EmpID = 0;
if (CheckBox1.Checked)
{
EmpID = 123;
arrEmpID.Add(EmpID);
}
if (CheckBox2.Checked)
{
EmpID = 1234;
arrEmpID.Add(EmpID);
}
if (CheckBox3.Checked)
{
EmpID = 1234;
arrEmpID.Add(EmpID);
}
After all i would like to assign this the EmpIDs
which was declared as int array
I tried this
for (int i = 0; i < arrEmpID.Coun开发者_如何学运维t; i++)
{
EmpIDs = arrEmpID.ToArray(new int[i]);
}
But i am unable to add can any one help me
You should avoid using ArrayList
. Instead use List<int>
, which has a method ToArray()
List<int> list = new List<int>();
list.Add(123);
list.Add(456);
int[] myArray = list.ToArray();
When converting an ArrayList to an array, you'll have to specify the type of the objects that it contains, and, you'll have to make sure you cast the result to an array of the desired type as well:
int[] empIds;
empIds = (int[])arrEmpID.ToArray(typeof(int));
But, as pointed out by others, why are you using an ArrayList
? If you're using .NET 1.1, you indeed have no other choice then using an ArrayList
.
However, if you're using .NET 2.0 or above, you should use a List<int>
instead.
Instead of the (old) ArrayList
class, use a (mordern) List<int>
. It's type safe and it has a ToArray method:
List<int> arrEmpID = new List<int>();
if (CheckBox1.Checked)
arrEmpID.Add(1234);
if (CheckBox2.Checked)
arrEmpID.Add(1234);
if (CheckBox3.Checked)
arrEmpID.Add(1234);
int[] EmpIDs = arrEmpID.ToArray();
In fact, you might consider using the List<int>
all along instead of creating an int[]
afterwards.
If you really need ArrayList
, you can try using the following:
EmpIDs = arrEmpID.OfType<int>().ToArray();
(But this is only available in .NET 3.5 and above)
try this:
EmpIDs = arrEmpID.ToArray(typeof(int));
try this.
EmpIDs= new int[arrEmpID.Count]; // initilise the array
for (int i = 0; i < arrEmpID.Count; i++)
{
EmpIDs[i] = arrEmpID[i]; // set each value
}
the fault with your code is that you are not initilizing the array to the size of the arrayList.
精彩评论