C#实现IComparable接口
可以用这个接口对自定义的类进行排序,排序方式还可以设置按照多种标准排序。使用起来非常的灵活,本栗子实现了用一个自定义类Box的长,宽,高进行排序。即,先比较长,如果长相等,再比较宽,如果宽也相等,再比较高。
class Program
{
static void Main(string[] args)
{
List<Box> Boxes = new List<Box>();
Boxes.Add(new Box(4, 20, 14));
Boxes.Add(new Box(12, 12, 12));
Boxes.Add(new Box(8, 20, 10));
Boxes.Add(new Box(6, 10, 2));
Boxes.Add(new Box(2, 8, 4));
Boxes.Add(new Box(2, 6, 8));
Boxes.Add(new Box(4, 12, 20));
Boxes.Add(new Box(18, 10, 4));
Boxes.Add(new Box(24, 4, 18));
Boxes.Add(new Box(10, 4, 16));
Boxes.Add(new Box(10, 2, 10));
Boxes.Add(new Box(6, 18, 2));
Boxes.Add(new Box(8, 12, 4));
Boxes.Add(new Box(12, 10, 8));
Boxes.Add(new Box(14, 6, 6));
Boxes.Add(new Box(16, 6, 16));
Boxes.Add(new Box(2, 8, 12));
Boxes.Add(new Box(4, 24, 8));
Boxes.Add(new Box(8, 6, 20));
Boxes.Add(new Box(18, 18, 12));
Boxes.Sort(new BoxLengthFirst());
foreach(var item in Boxes)
{
PrintBox(item);
}
Console.ReadKey();
}
static void PrintBox(Box box)
{
Console.WriteLine($"Length:{box.Length.ToString("00")}\tWidth:{box.Width.ToString("00")}\tHeight:{box.Height.ToString("00")}");
}
}
// BoxLengthFirst
public class BoxLengthFirst : Comparer<Box>
{
// Compares by Height,Length,Width
public override int Compare(Box x, Box y)
{
if(x.Length.CompareTo(y.Length)!=0)
{
return x.Length.CompareTo(y.Length);
}
else if (x.Width.CompareTo(y.Width) != 0)
{
return x.Width.CompareTo(y.Length);
}
else if(x.Height.CompareTo(y.Height)!=0)
{
return x.Height.CompareTo(y.Height);
}
else
{
return 0;
}
}
}
// Class Box
public class Box : IComparable<Box>
{
public int Length { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public Box(int l, int w, int h)
{
this.Height = h;
this.Width = w;
this.Length = l;
}
public int CompareTo(Box other)
{
// Compares Height,Length,Width
if (this.Height.CompareTo(other.Height) != 0)
{
return this.Height.CompareTo(other.Height);
}
else if (this.Width.CompareTo(other.Width) != 0)
{
return this.Width.CompareTo(other.Width);
}
else if (this.Length.CompareTo(other.Length) != 0)
{
return this.Length.CompareTo(other.Length);
}
else
{
return 0;
}
}
}