简体   繁体   中英

Sort and IList of numbers in ascending order c#

So I came across over this problem which I thought is quite easy but got me thinking. The task is to sort an Ilist of numbers in ascending order. As far as I understood we can't use Sort() method for Ilists, since it is not build in the intreface. Could you please help me what would be the best and simple solution to sort an Ilist?

IList<int> list = new List<int>() { -5, 8, -7, 0, 44, 121, -7 };

You can simply use Linq for the task:

var list = new List<int>() { -5, 8, -7, 0, 44, 121, -7 };
var sorted = list.OrderBy(x => x);

If you want to do an in-place sort, you can use ArrayList.Adapter()

As per the documentation:

The ArrayList class provides generic Reverse, BinarySearch and Sort methods. This wrapper can be a means to use those methods on IList; however, performing these generic operations through the wrapper might be less efficient than operations applied directly on the IList.

if you know the unterlying type of your IList you can cast to List and use Sort method.

((List<int)list).Sort()

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