- Home /
c# string[][] to Arraylist problems
Hi folks!
i want to convert a multidimensional array "string[][] theArray" into an ArrayList and then read out one of the partial arrays "string[] theStringArray".
the problem is that i get the error that i want to convert an object into a string[].
my code is
void myFunction(int cnt) { ArrayList tmpList = ArrayToArrayList(theArray); int counter = cnt/2;
while (counter-- >= 1)
{
int lengthOfList = tmpList.Count;
int rndM = Random.Range(0, lengthOfList - 1);
string[] tmpPair = tmpList[rndM]; // <--- HERE I GET THE ERROR !!!
tmpList.RemoveAt(rndM);
//...
}
}
ArrayList ArrayToArrayList(string[][] theArray) { ArrayList theList = new ArrayList(); for (int i = 0; i < theArray.Length; i++){ string[] tmp = theArray[i]; theList.Add(tmp); } return theList; }
so whats my problem (besides that I am new to c#)? thanx!
i forgot to mention that theArray is "private static string[][] theArray"
Answer by Mike 3 · Aug 24, 2010 at 04:08 PM
You need to be casting to string[] when you grab something from the arraylist:
string[] tmpPair = (string[])tmpList[rndM];
Ideally you'd modify the code to use List instead though, that way the code should be cleaner and you won't need to cast everywhere
List<string[]> tmpList = ArrayToList(theArray); string[] tmpPair = tmpList[rndM]; //will just work
List<string[]> ArrayToList(string[][] theArray) { List<string[]> theList = new List<string[]>(); //rest is the same
You'll need to have
using System.Collections.Generic;
at the top for that to work
hm, but when I then try to add the randomly chosen list-entry to another List ("anotherListDeclaredOutside.Add(tmpPair);") in the while-loop, I get the error "NullReferenceException: Object reference not set to an instance of an object"...
I can't immediately see why that'd be, it could be the bug you have with the range though. You need to use Random.Range(0, lengthOfList) ins$$anonymous$$d of the one you have with -1, the top value for Range with an int isn't included already
I think you'll have to post the rest of the code, it sounds like it's just a case of the other list not being instantiated
Your answer
Follow this Question
Related Questions
ArrayList Transform type! 2 Answers
C# ArrayList access from other script 1 Answer
Problem with multi prefabs collision 1 Answer
how to change a variable from? an object in this array with a gui.button 0 Answers
Adding Waypoints using a List 2 Answers