简体   繁体   中英

sorting a large list of doubles in descending order

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?

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).

除了Vlad指出的之外,如果您想对列表进行就地排序,而不创建新列表,请尝试使用Sort方法的此重载

xlist.Sort((a, b) => Math.Sign(b - a));

另一种方法是使用List.Sort方法和以下降序比较器作为参数:

xlist.Sort((a, b) => b.CompareTo(a));

You can sort it like this:

var sortedList = from element in xlist
                 orderby element descending
                 select element;

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM