在使用List<>的时候,有可能需要对List中内容进行排序,可以使用List的内置排序机制Sort方法进行排序,但是List中的数据类型需要实现IComparable借口。
在下面的例子中 Square就实现了IComparable借口,根据面积进行排序:
class Program
{
static void Main(string[] args)
{
var data = new List<Square>() { new Square(5, 10), new Square(2, 3), new Square(1, 8), new Square(4,6) };
foreach (var d in data)
Console.WriteLine(d.ToString());
data.Sort();
foreach (var d in data)
Console.WriteLine(d.ToString());
Console.ReadKey();
}
}
public class Square : IComparable<Square>
{
public Square(int height, int width)
{
Height = height;
Width = width;
}
public int Height { get; set; }
public int Width { get; set; }
public int CompareTo(object obj)
{
Square square = obj as Square;
if (square != null)
CompareTo(square);
throw
new ArgumentException("Both objects being compared be of type Square");
}
public override string ToString() => ($"Height:{this.Height} Width:{this.Width}");
public int CompareTo(Square other)
{
long area1 = this.Height * this.Width;
long area2 = other.Height * other.Width;
if (area1 == area2)
return 0;
if (area1 > area2)
return 1;
return -1;
}
}
输出结果:
如果字典类型想要排序,可以使用SortedDictionary<TKey, TValue>
类型,在使用add方法是会进行排序
例:
var dic = new SortedDictionary<int, Square>() { { 0, new Square(5, 10) }, { 1, new Square(2, 3) }, { 2, new Square(1, 8) }, { 3, new Square(4, 6) } };
输出结果:
如果别人定义一个数据类型,却未提供排序方法,而你有无法修改这个数类型时,可以使用IComparer 接口。下面例子定义了CompareHeight,实现IComparer接口,对Square对象的高度进行排序。
例:
ublic class CompareHeight : IComparer<Square>
{
public int Compare(Square x, Square y)
{
if (x.Height == y.Height)
return 0;
if (x.Height > y.Height)
return 1;
return -1;
}
}
p
使用代码:
var data1 = new List<Square>() { new Square(5, 10), new Square(2, 3), new Square(1, 8), new Square(4, 6) };
data.Sort(new CompareHeight());
结果:
另外还可以使用lambda表达式实现:
data.Sort((x, y) =>
{
if (x.Height == y.Height)
return 0;
if (x.Height > y.Height)
return 1;
return -1;
});
结果也是一样的。