Files
2025-10-21 20:37:12 +08:00

146 lines
4.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Generic;
namespace Lesson16_List排序
{
class Program
{
static void Main(string[] args)
{
#region 知识点一 List自带的排序方法
List<int> list = new List<int>();
list.Add(3);
list.Add(2);
list.Add(4);
list.Add(6);
list.Add(5);
list.Add(1);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine("_________________________");
//list提供了sort方法,可以对list进行排序,默认是升序排序
list.Sort();
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
//Arraylist中也有sort方法
#endregion
#region 知识点二 自定义类的排序
Console.WriteLine("_________________________");
List<Item> itemList = new List<Item>();
itemList.Add(new Item(45));
itemList.Add(new Item(10));
itemList.Add(new Item(99));
itemList.Add(new Item(24));
itemList.Add(new Item(100));
itemList.Add(new Item(12));
itemList.Sort();//无法排序,自定义类没有默认的排序规则,不知道按哪个字段排序
for (int i = 0; i < itemList.Count; i++)
{
Console.WriteLine(itemList[i].money);
}
#endregion
#region 知识点三 通过委托函数进行排序
List<ShopItem> shopItems = new List<ShopItem>();
shopItems.Add(new ShopItem(5));
shopItems.Add(new ShopItem(2));
shopItems.Add(new ShopItem(3));
shopItems.Add(new ShopItem(6));
shopItems.Add(new ShopItem(4));
shopItems.Add(new ShopItem(1));
//通过委托函数进行排序
//shopItems.Sort(SortShopItem);
//通过匿名函数表达式进行排序
//shopItems.Sort(delegate(ShopItem a,ShopItem b) {
// if (a.price > b.price)
// {
// return 1;
// }
// else if (a.price == b.price)
// {
// return 0;
// }
// else
// {
// return -1;
// }
//});
//通过lambda表达式结合三木运算符进行排序
shopItems.Sort((a, b) => {
return a.price > b.price ? 1 : -1;
});
Console.WriteLine("_________________________");
for (int i = 0; i < shopItems.Count; i++)
{
Console.WriteLine(shopItems[i].price);
}
#endregion
}
static int SortShopItem(ShopItem a,ShopItem b)
{
if (a.price > b.price)
{
return 1;
}else if (a.price == b.price)
{
return 0;
}
else
{
return -1;
}
}
}
class Item : IComparable<Item>
{
public int money;
public Item(int money)
{
this.money = money;
}
public int CompareTo(Item other)
{
//返回值的含义:
//小于0
//相当于放在当前对象前面
//等于0
//保持当前的位置不变
//大于0
//相当于放在当前对象后面
if ( this.money > other.money)
{
return 1;
}else if (this.money == other.money)
{
return 0;
}
else
{
return -1;
}
}
}
class ShopItem
{
public int price;
public ShopItem(int price)
{
this.price = price;
}
}
}
//总结:
//系统自带的变量(int, float, double......) 一般都可以直接 Sort
// 自定义类 Sort 有两种方式
// 1. 继承接口 IComparable
// 2. 在 Sort 中传入委托函数