Reputation: 5409
I'm trying to have nested ArrayLists, and tried to add a new ArrayList as an element of an existing one, but it doesn't seem to work. Here's the code:
private void readDataFile()
{
// Open stream reader
StreamReader reader = new StreamReader(dataFileLoc);
string line = string.Empty;
line = reader.ReadLine();
myArgus.Add(new ArrayList().Add(line));
while ((line = reader.ReadLine()) != null)
{
// TODO
}
// Close the reader
reader.Close();
}
If I add a breakpoint and look at the data in myArgus
(the already existing ArrayList), the first element is just 0
. It should be an ArrayList which has the first element as 10016
(that's the first line of the text file).
What am I doing wrong here?
Thanks!
Edit: It's worth noting that we are required to use an ArrayList.
Upvotes: 0
Views: 3625
Reputation: 100547
ArrayList.Add does not return ArrayList, but simply int.
So you want to add elements in 2 steps.
int index = myArgus.Add(new ArrayList());
((ArrayList)myArgus[index]).Add(line);
Note: Use strongly typed collections (List<string>
) to avoid this type of errors.
Upvotes: 3
Reputation: 2364
You can technically still do it in one step
myArgus.Add(new ArrayList() { line } );
Upvotes: 2
Reputation: 172260
This line:
myArgus.Add(new ArrayList().Add(line));
adds 0
as the first element to myArgus
. Why? Because the return value of ArrayList.Add is defined as follows:
Return Value
Type: System.Int32
The ArrayList index at which the value has been added.
Since your new ArrayList()
does not contain any items, line
is added at index 0
.
What you probably meant to write was:
var subList = new ArrayList();
subList.Add(line);
myArgus.Add(subList);
In fact, what you should do is to use typed lists:
List<List<string>> myArgus;
This helps catch this kind of error, because the compiler complains if an int
is added instead of the expected List<string>
.
Upvotes: 3