-4

I have a problem with this function:

 static List<int> transposition(List<List<int>> main_list, int ammount)
    {
        List<int> return_list = new List<int>();
        List<int> b = new List<int>();
        List<List<int>> new_list = new List<List<int>>();
        new_list = main_list;
        int i = 0;
        int j = 0;
        int x = 0;
        int key = 0;
        Random rnd = new Random();
        foreach (List<int> subList in new_list)
        {
            x = subList[2];
        }
        while (i < ammount)
        {
            i++;
            key = rnd.Next(0, x + 1);
            while (j < new_list.Count)
            {
                if (key >= new_list[j][1] && key <= new_list[j][2])
                {
                    List<int> one_element = new List<int>();
                    one_element.Add(new_list[j][0]);
                    one_element.Add(new_list[j][1]);
                    one_element.Add(new_list[j][2]);
                    one_element.Add(new_list[j][3]);
                    if (j != 0)
                    {
                        b = new_list[j - 1];
                        new_list[j - 1] = one_element;
                        new_list[j] = b;
                    }
                }
                j++;
            }
        }
        foreach (List<int> element in new_list)
        {
            return_list.Add(element[3]);
        }
        return return_list;
    }

As you can see I'm passing 'main_list' to this function and the problem is that this list changes in the function. I had the same problem in Python and there I solve the problem by adding [:], like this 'new_list = main_list[:]'. But I haven't found how to do this in c#. Any suggestions?

Sergei Petrov
  • 93
  • 1
  • 2
  • 10
  • 4
    Possible duplicate of [Changes made on "copy" list are reflecting original list - c#](https://stackoverflow.com/questions/39633104/changes-made-on-copy-list-are-reflecting-original-list-c-sharp) – Broots Waymb Dec 26 '17 at 13:58
  • 1
    Why instantiating a list when you don't want to use that object? – Sunil Dec 26 '17 at 14:04

1 Answers1

-1

instead of

List<List<int>> new_list = new List<List<int>>();
new_list = main_list;

do

List<List<int>> new_list = new List<List<int>>(main_list);

this creates a new list which takes its content from main_list. you created an independent copy of your main_list.