定义Car类,包含两个字段:name和price; (2)在Main方法中,使用Array.Sort方法对Car对象数组根据姓名和价格排序。

/*破ide 时好时不好,搞的我以为代码有问题,重建工程后,一切正常, 这是搞毛线,越来越厌恶cjing*/
using System;
using System.Collections;

public class Car
{
    public string name;
    public double price;

    public Car(string name, double price)
    {
        this.name = name;
        this.price = price;
    }

    public override string ToString()
    {
        return string.Format("Car`s name:{0}, price:{1}", name, price);
    }
}

public class PriceComparer : IComparer
{
    public int Compare(Object obj1, Object obj2)
    {
        Car c1 = obj1 as Car;
        Car c2 = obj2 as Car;

        if (c1.price >= c2.price)
            return -1;
        return 1;
    }
}

public class NameComparer : IComparer
{
    public int Compare(Object obj1, Object obj2)
    {
        Car c1 = obj1 as Car;
        Car c2 = obj2 as Car;

        return string.Compare(c1.name, c2.name);
    }
}
public class Example
{
    public static void Main()
    {
        Car[] cars = new Car[4];
        for (int i = 0; i < 4; i++)
        {
            cars[i] = new Car("car" + i, i);
        }

        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine(cars[i].ToString());
        }
        IComparer priceComparer = new PriceComparer();

        
        Array.Sort(cars, priceComparer);

        Console.WriteLine("按价格排序后的:");
        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine(cars[i].ToString());
        }

        IComparer nameComparer = new NameComparer();
        Array.Sort(cars, nameComparer);

        Console.WriteLine("按名字排序后的:");
        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine(cars[i].ToString());
        }
        Console.Read();
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值