C#按照List属性值排序

本文介绍了一种使用自定义比较器对图书列表进行排序的方法,包括按书名升序和价格升序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 protected void btnSort_Click(object sender, EventArgs e)
    {
        List<Book> list = new List<Book>();
        Book b1, b2, b3, b4;
        b1 = new Book("《绝代双骄》", "古龙", "中国长安出版社", 50);
        b2 = new Book("《鹿鼎记》", "金庸", "人民文学出版社", 120);
        b3 = new Book("《三国演义》", "罗贯中", "中州古籍出版社", 200);
        b4 = new Book("《西游记》", "吴承恩", "晨光出版社", 80);
        list.Add(b1);
        list.Add(b2);
        list.Add(b3);
        list.Add(b4);

        //按书名升序
        Response.Write("/////////////按书名升序/////////////<br />");
        list.Sort(new Icp());
        foreach (Book book in list)
        {
            Response.Write(book.Name + book.Author + book.Publisher + book.Price + "<br />");
        }
        Response.Write("////////////////////////////////////<br />");

        //按价格降序序
        Response.Write("/////////////按价格升序/////////////<br />");
        list.Sort(new IcpPrice());
        foreach (Book book in list)
        {
            Response.Write(book.Name + book.Author + book.Publisher + book.Price + "<br />");
        }

    }
==============================================================
public class Book
{
    public Book(string inname, string inauthor, string inpublisher, int inprice)
    {
        this.Name = inname;
        this.Author = inauthor;
        this.Publisher = inpublisher;
        this.Price = inprice;
    }

    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    private string author;

    public string Author
    {
        get { return author; }
        set { author = value; }
    }
    private string publisher;

    public string Publisher
    {
        get { return publisher; }
        set { publisher = value; }
    }
    private int price;

    public int Price
    {
        get { return price; }
        set { price = value; }
    }
}

//比较器类
public class Icp : IComparer<Book>
{
    //按书名排序
    public int Compare(Book x, Book y)
    {
        return x.Name.CompareTo(y.Name);
    }
}

public class IcpPrice : IComparer<Book>
{
    //按价格排序
    public int Compare(Book x, Book y)
    {
        return x.Price.CompareTo(y.Price);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值