Vlad Vv
Vlad Vv

Reputation: 13

Can't create nested list because list.Clear doesn't seem to work as I want

I try to load txt file that consists of 200 rows each of different length into nested list so that every sublist inside main list will be equal to row, so there will be 200 sublists.

class MainClass
{
        public static void Main (string[] args)
        {
            List<List<int>> arrayList = new List<List<int>>();
            List<int> tmp = new List <int> ();
            string[] file = File.ReadAllLines(@"C:\file.txt");

            foreach (string line in  file) {
                string[] linef = line.Split (new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                tmp.Clear ();

                for (int n = 0; n < linef.Length; n++) {
                    tmp.Add (int.Parse (linef [n]));
                }

                arrayList.Add (tmp);
            }

But arrayList seams to contain only last row - whenever i try to get some number, for a example arrayList[78][5], it gives me 5th number from 200th row no matter what the first index is - 78 or other. I think there is issue with tmp.Clear but i cant figure out how to make it work.

Upvotes: 0

Views: 206

Answers (2)

vojta
vojta

Reputation: 5651

tmp.Clear() makes your list empty, that is all. The main list contains only 200 references to your tmp list. You have to call

tmp = new List<int>();

instead of

tmp.Clear();

Upvotes: 0

xanatos
xanatos

Reputation: 111840

Because you are re-adding the same List<int> tmp many times to arrayList, so that at the end

 bool areSame = object.ReferenceEquals(arrayList[0], arrayList[1]); // true

You have one List<int> with n references to it (one for each "row" of arrayList)

Change it to:

 foreach (string line in  file) {
     List<int> tmp = new List <int> ();
     // No Clear necessary

Upvotes: 1

Related Questions