Lists inside list in C# -
This is working with my first time collection and I'm stuck here, I tested it for a test project I have made a problem and I do not know how to work around
First of all, I want to do lists with particular lists (cant use anything), there is a large list with the inside list, like this:
< Code> list & lt; List & lt; Int & gt; & Gt; Allnums = new list & lt; List & lt; Int & gt; & Gt; ();The number I want to add to the previous list is collected here:
list & lt; Int & gt; Nums = new list & lt; Int & gt; ();
So far, very good.
I have to add indexes indefinitely to my main list (Allnums), so I have nums1, nums2, Num3 ... etc
OK, let's have a random Try num to add numbers: (only 1 number for now)
random rnd = new random (); Private Zero Button 1_Click (Object Sender, EventArgs e) {nums.Add (rnd.Next (10)); }
Now, let's save the number that has been generated and clear the nums list to store the new number next time (Show store 4 lists only).
Private Zero Button 2_Click (Object Sender, EventArgs e) {Allnums.Add (nums); // Adds a small list to the main list nums.Clear (); // clears a small list to accept new values}
Check the results with this code:
Private Zero Button 3_Click (Object Sender, EventArgs e) {listBox1.Items.Clear (); ListBox1.Items.Add ("Number of listings entered:" + Allnums.Count); Forward (list & amp; lt; int & gt; number list in Akhilnam) {listBox1.Items.Add ("----------"); // divide divider list foreach (int number in numlist) {listBox1.Items.Add (number); }}}
I get this:
Number of listings entered: 4 // OK ---------- // List1: nothing ---------- // list 2: nothing ---------- // list 3: nothing ---------- // list 4: nothing
As you see, not all numbers are there. But if I 'nums.Clear ();' In the 'Button 2_Click' event, I get this:
Number of listings entered: 4 // OK ---------- // list 1 0 5 9 1 ---- ------ // list 2 0 5 9 1 ---------- // list 3 0 5 9 1 ---------- // list 4 0 5 9 1 // All incorrect
It stores all the values, but wrongly, because what I want to achieve is this:
Number of entries entered: 4 - --------- // list 1 0 ---------- // list 2 5 -------- - // list 39 --------- - // list 4 1
Am I wrong? Is there anything else I can do? Please help, thanks for reading.
Edit: As @CrashMast said,
list is a reference type A better solution would be:
AllNums.Add (nums); Nums = new list & lt; List & lt; Int & gt; & Gt; ();
======================================= ========================
In your
button 2_Click function, you will see
nums < There is a need to make a copy of / code> Allnums will do something like this before adding it:
var newNums = nums.ToArray (). ToList (); Allnums.Add (newNums);
Comments
Post a Comment