排序方式
- 使用List.Sort(),并实现IComparable接口
- 使用List.Sort(委托)
排序步骤
- 排序时返回的 int 值,提取两个对象的信息
- 相减进行比x大值的在前面,就是升序
例子:
public class TestObject
{
public int n;
public bool b;
public override string ToString()
{
return string.Format("[{0},{1}]\t", n, b); ;
}
}
static void Main(string[] args)
{
List<TestObject> testObjects = new List<TestObject>{
new TestObject() { n = 1, b=true },
new TestObject() { n = 5, b=true },
new TestObject() { n = 3,b=false },
new TestObject() { n = 7,b=true },
new TestObject() { n = 2, b=false},
};
Console.WriteLine("默认");
Output(testObjects);
Console.WriteLine();
Console.WriteLine("升序");
testObjects.Sort(UpSort);
Output(testObjects);
Console.WriteLine();
Console.WriteLine("布尔");
testObjects.Sort(BoolSort);
Output(testObjects);
}
private static void Output(List<TestObject> testObjects)
{
foreach (var item in testObjects)
{
Console.Write(item + " ");
}
}
/// <summary>
/// 升序
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
private static int UpSort(TestObject x, TestObject y)
{
return x.n - y.n;
}
/// <summary>
/// 布尔
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
private static int BoolSort(TestObject x, TestObject y)
{
//前面的比后面的大就是交互位置,然后大的在后面
return (x.b ? 0 : 1)-(y.b ? 0 : 1);
}