排序不同类型的对象

时间:2018-10-08 13:21:10

标签: c#

我有3种具有相同基类的对象。用相同的基类制作对象数组的最佳方法是什么? 我必须创建通用类型并使用Comparer来做到这一点,还是有一种方法可以使用某些arraylist类呢?

我需要按类型和按字段对对象进行排序。 像这样:coupe1,coupe2,sedan1,sedan2,sedan3,hatchback1等,以及所有数组元素的字段。

class Program
{
    abstract class Car
    {
        public string Name { get; set; }
        public int Maxspeed { get; set; }                      
        public override string ToString() { return Name + " | " + Maxspeed.ToString();}
    }
    class Coupe : Car
    {
        public Coupe(string name, int maxspeed){ Name = name; Maxspeed = maxspeed;}
    }
    class Sedan : Car
    {
        public Sedan(string name, int maxspeed) { Name = name; Maxspeed = maxspeed;}
    }
    class Hatchback : Car
    {
        public Hatchback(string name, int maxspeed){  Name = name; Maxspeed = maxspeed;}
    }
    class Cars<T>:IComparer<T> where T:Car
    {
        private T[] cars;
        private int length;
        public int Length
        {
            get{ return length;}

        }
        public Cars(int i)
        {
            if (i > 0){ cars = new T[i]; length = i;}\
        }
        public T this[int i]
        {
            get {return cars[i];}
            set{cars[i] = value;}
        }



        public int Compare(T x, T y)
        {
            throw new NotImplementedException();
        }
    }

    static void Main(string[] args)
    {
        Coupe coupe1 = new Coupe("Audi R8", 250);
        Sedan sedan1 = new Sedan("Suzuki Ciaz", 180);
        Hatchback hatchback1 = new Hatchback("Hyundai Elantra", 170);
        Cars<Car> cars = new Cars<Car>(3);
        cars[0] = coupe1;
        cars[1] = sedan1;
        cars[2] = hatchback1;
        for (int i = 0; i < cars.Length; i++)
            Console.WriteLine(cars[i].Name + " " + cars[i].Maxspeed.ToString());

        Console.ReadKey();
    }
}

1 个答案:

答案 0 :(得分:3)

如果您只有List<Car>,则可以使用LINQ OrderBy来按类型先排序,然后按其他方式排序

Coupe coupe1 = new Coupe("Audi R8", 250);
Sedan sedan1 = new Sedan("Suzuki Ciaz", 180);
Hatchback hatchback1 = new Hatchback("Hyundai Elantra", 170);
List<Car> cars = new List<Car>(3);
cars.Add(coupe1);
cars.Add(sedan1);
cars.Add(hatchback1);
var orderedByTypeThenSpeedDescending = cars.OrderBy(x => x.GetType())
                                           .ThenByDescending(x => x.MaxSpeed);