Skip to main content
 首页 » 编程设计

c#之在 C# 中,按最后一个元素对数组进行排序

2024年02月13日12daizhj

如果我有一个如下所示的二维数组,是否可以按最后一个元素对数组进行排序? (最后一个元素表示 2、10、1、5)

string[,] original = new string[4, 3] { {"apple","price1", "2"}, {"orange","price2", "10"} , {"Pineapple","price5", "1"}, {"Kiwi","price3", "5"}}; 

请您参考如下方法:

这并没有直接回答问题,但更简洁的实现可能类似于...

public class Fruit : IComparer<Fruit>, IComparable<Fruit> 
    { 
        public Fruit(string name, double price, int quantity) 
        { 
            Name = name; 
            Price = price; 
            Quantity = quantity; 
        } 
 
        protected int Quantity { get; set; } 
 
        protected double Price { get; set; } 
 
        protected string Name { get; set; } 
 
        public int CompareTo(Fruit other) 
        { 
            if (Quantity < other.Quantity) return 1; 
            if (Quantity > other.Quantity) return -1; 
            return 0; 
        } 
 
        public override string ToString() 
        { 
            return string.Format("{0} {1} {2}", Name, Price, Quantity); 
        } 
 
        public int Compare(Fruit x, Fruit y) 
        { 
            if (x.Quantity > y.Quantity) return 1; 
            if (x.Quantity < y.Quantity) return -1; 
            return 0; 
        } 
    } 

然后你可以像这样使用新类......

var fruits = new List<Fruit> 
                { 
                    new Fruit("Apple", 0.30, 2), 
                    new Fruit("Orange", 0.50, 10), 
                    new Fruit("Pineapple", 0.35, 1), 
                    new Fruit("Kiwi", 0.33, 5) 
                }; 
 
 
            Console.WriteLine("Before sort"); 
            foreach (var fruit in fruits) 
            { 
                Console.WriteLine(fruit.ToString()); 
            } 
 
            fruits.Sort(); 
            Console.WriteLine("After sort"); 
            foreach (var fruit in fruits) 
            { 
                Console.WriteLine(fruit.ToString()); 
            } 
 
            fruits.Reverse(); 
            Console.WriteLine("After reverse"); 
            foreach (var fruit in fruits) 
            { 
                Console.WriteLine(fruit.ToString()); 
            } 
 
            Console.ReadLine(); 

输出: