Reputation: 127
I want to maintain the list order after sorting. For example, the user enter 2, 4, 7, 1, 0 to be added to the list. How can I maintain this order after using the static sorted method on the list? I tried using a bubble sort method and copy the original list in another list variable, but after passing the list to below sorted method, it sorts the original list even thought it was copied in another list variable.
Is there anyway around this?
private List<int> sortedList(List<int> sortedGrads)
{
for (int i = 0; i < sortedGrads.Count - 1; i++)
{
for (int j = 0; j < sortedGrads.Count - 1 - i; j++)
{
if (sortedGrads[j] > sortedGrads[j + 1])
{
int temp = sortedGrads[j];
sortedGrads[j] = sortedGrads[j + 1];
sortedGrads[j + 1] = temp;
}
}
}
return sortedGrads;
}
Upvotes: 0
Views: 1302
Reputation: 21
To get the sorted list use LINQ and store the result in other variable and keep your original list as it is.
private List<int> sortedList(List<int> sortedGrads)
{
List<int> sortedElements = sortedGrads.OrderBy(x => x).ToList();
//use any one from below
return sortedGrads; //returns the original list
return sortedElements; //returns the sorted list
}
Upvotes: 2