Sort List<int> ">" and "<"

本文关键字:quot lt gt and int Sort List | 更新日期: 2023-09-27 17:53:42

如何将List<int> {1,4,2,56,7}从最小到最大,从最大到最小排序?我尝试了一些东西,比如

List<int> sorted = Listname.Sort();

List<int> sorted = Listname.OrderByDescending();

但是我不完全理解语法

Sort List<int> ">" and "<"

您可以使用LINQ:

var smallToLarge = Listname.OrderBy(x => x);
var largeToSmall = Listname.OrderByDescending(x => x);

如果你想把它们分配给一个列表,就像在你的问题中的代码示例一样,你必须在每一个之后调用.ToList()

   class Program
    {
        static void Main(string[] args)
        {
            List<int> listOfInts = new List<int>() { 1, 4, 2, 56, 7 };
            listOfInts.Sort();
            foreach (int ii in listOfInts)
            {
                Console.WriteLine("{0}", ii);
            }
            Console.WriteLine("Descending ...");
            listOfInts.Reverse();
            foreach (int ii in listOfInts)
            {
                Console.WriteLine("{0}", ii);
            }
            Console.WriteLine("Hit any key to continue");
            Console.ReadKey();
        }
    }

按升序和降序排序

List<int> ints = new List<int>() { 1, 4, 2, 56, 7 };
ints.Sort(); // by asc
ints.Reverse(); //by desc