Reputation: 43
I have a rather large list consisting of several thousand doubles and I wish to sort it in descending order.
xlist
is my list of doubles.
I tried
xlist.Sort();
xlist.Reverse();
and
xlist.OrderByDescending(d => d);
Then I proceed to use for loop to print out the contents of the list. Neither of these work. What should I do?
Upvotes: 2
Views: 7991
Reputation: 1582
You can sort a list using OrderByDescending(d => d) under System.Linq. The function above will return a new list instance instead of sorting the list itself. So your final code should be:
xlist = xlist.OrderByDescending(d => d).ToList();
Now if your list contains a two dimensional array, you can sort the list by specifying the value needed in the array. for example:
double[] arr1 = {1, 2, 3};
double[] arr2 = {5, 6, 8};
List<double[]> Items = new List<double[]>();
Items.Add(arr1);
Items.Add(arr2);
Items = Items.OrderByDescending(d => d[2]).ToList();
The list will be sorted by the 2nd value of the array (6 and 2)
Upvotes: 0
Reputation: 1919
You are not assigning the sorted list to the variable. You probably want:
xlist = xlist.OrderByDescending(d => d).ToList();
Example:
IList<double> list = new List<double>() { 10, 22, 71.2, 12.4, 1.78, 90.1, 107.33, 5.9 };
System.Diagnostics.Debug.WriteLine("Unsorted: " + string.Join(",", list));
list = list.OrderByDescending(d => d).ToList();
System.Diagnostics.Debug.WriteLine("Reverse Sorted: " + string.Join(",", list));
Output:
Unsorted: 10,22,71.2,12.4,1.78,90.1,107.33,5.9
Sorted: 107.33,90.1,71.2,22,12.4,10,5.9,1.78
Performance: It took 0.41 seconds to sort 1,000,000 random double values (if you consider that to be a large list).
Upvotes: 9
Reputation: 14059
Alternative way is to use the List.Sort
method with the following descending comparer as the argument:
xlist.Sort((a, b) => b.CompareTo(a));
Upvotes: 3
Reputation: 149010
In addition to what Vlad pointed out, if you want to sort the list in place, without creating a new list, try using this overload of the Sort
method:
xlist.Sort((a, b) => Math.Sign(b - a));
Upvotes: 4
Reputation: 3915
You can sort it like this:
var sortedList = from element in xlist
orderby element descending
select element;
Upvotes: 0