Home > Net >  How do I sort a cloned temp list in a while loop without also sorting the original list(C#)?
How do I sort a cloned temp list in a while loop without also sorting the original list(C#)?

Time:01-10

I copied an int list into a temporary list in a while loop so I could sort it without sorting the original. For some reason both get sorted when I do this and I don't understand why.

public static int sortedSum(List<int> a)
{
    int ans = 0;
    while (a.Count > 0)
    {
        var temp = a;
            
        temp.Sort();

        for (int i = 0; i < a.Count; i  )
        {
            ans  = temp[i] * (i   1);
        }
        a.RemoveAt(a.Count - 1);
    }
    return ans;
}

The Problem I was trying to solve requires me to keep removing the last index spot and then sorting the list. I thought cloning the list would allow me to manipulate the list without messing with the index spots of the original but when I sort the Temp list the original gets sorted as well. I suspect this is a function of the while loop, but if so I'm confused at to why the "a" list would take on the characteristics of the temp list and not vise versa as the "var temp = a;" would suggest. I was able to work around the problem by converting temp to an int array and sorting that, but I'm still curious as to what's going on here.

CodePudding user response:

I copied an int list into a temporary list

No you didn't - var temp = a; does not create a copy of the list - they are referencing the same list.

I would just do

var temp = a.OrderBy(x => x).ToList();

if you want a separate, sorted list. There may even be more efficient ways to do what you're trying to do, but your logic is not clear enough to make a better suggestion.

  • Related