Bar Ittah
Bar Ittah

Reputation: 51

Remove element from nested list C#

I am trying to work with list of lists. how do I remove a specific element from the list? I have the following code:

using System;
using System.Collections.Generic;
namespace TEST3
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            List<List<int>> ar = new List<List<int>> ();
            List<int> innerAr = new List<int> ();
            for (int i = 1; i <= 9; i++) 
            {
                innerAr.Add (i);
            }
            for (int j = 0; j <= 80; j++) 
            {
                ar.Add (innerAr);
            }
            ar[80].RemoveAt(7);
            ar[80].RemoveAt(2);
            Console.WriteLine (ar[80].Count);
            Console.WriteLine (ar[79].Count);
        }
    }
}

Upvotes: 0

Views: 2130

Answers (4)

user786
user786

Reputation: 4364

You have parent list

 List<List<int>> parent=new List<List<int>>();

And your child list

List<int> child=new List<int>(){1,2,3};

Adding to parent

parent.Add(child);

child elements 1,2,3

Removing

parent[0].removeAt(0)

child elements 2,3

Upvotes: 0

adricadar
adricadar

Reputation: 10209

The lists have the same Count because is the same list added multiple times.

If you want just one list to be changed due to RemoveAt, you have to create a new one. A simple way to create a new list with same elements is to add ToList().

public static void Main(string[] args)
{
    List<List<int>> ar = new List<List<int>>();
    List<int> innerAr = new List<int>();
    for (int i = 1; i <= 9; i++)
    {

        innerAr.Add(i);
    }
    for (int j = 0; j <= 80; j++)
    {
        ar.Add(innerAr.ToList()); // <- here is the change
    }
    ar[80].RemoveAt(7);
    ar[80].RemoveAt(2);
    Console.WriteLine(ar[80].Count); // 7
    Console.WriteLine(ar[79].Count); // 9
}

Upvotes: 0

Guy
Guy

Reputation: 1502

Your removal is successful. As Charles hinted your only mistake is that the Object innerAt, is the exact same object that is in each of the 80 lists of List. since List is an object reference and not a value, you have the same reference in ar[79] and ar[80]

Upvotes: 0

poke
poke

Reputation: 387677

for (int j = 0; j <= 80; j++) 
{
    ar.Add (innerAr);
}

All elements in ar now contain the same reference to innerAr. There is only a single list that you kept adding to ar, so when you later change innerAr by accessing ar[80], then you also change the innerAr of all the other elements (because it’s the same list).

If you want independent list, you need to create one for each ar item:

List<List<int>> ar = new List<List<int>>();
for (int j = 0; j <= 80; j++) 
{
    List<int> innerAr = new List<int>();
    for (int i = 1; i <= 9; i++) 
    {
        innerAr.Add(i);
    }
    ar.Add(innerAr);
}

Upvotes: 1

Related Questions