对于基本类型的普通排序
直接调用Sort()方法
List<int> listBase = new List<int>() { 128, 25, 81 };
Console.WriteLine("基础类型排序前(List<int>):");
foreach (var item in listBase)
{
Console.Write($"{item} \t"); // result: 128 25 81
}
Console.WriteLine("\n基础类型排序后(List<int>):");
// 排序方法一:Sort()
listBase.Sort(); // 升序排序 result: 25 81 128
//listBase.Reverse(); //反转 result: 81 25 128
//排序方法二:使用lambda表达式,前面加个负号:
//listBase.Sort((x, y) => x.CompareTo(y)); //升序
//listBase.Sort((x, y) => -x.CompareTo(y)); //降序序
foreach (var item in listBase)
{
Console.Write($"{item} \t");
}
实现IComparable接口
根据单个值排序
public class Part : IComparable<Part>
{
public int PartId { get; set; }
public string PartName { get; set; }
public override string ToString()
{
return $"ID: {PartId}\t{PartName}";
}
public int CompareTo(Part comparePart)
{
if (comparePart == null)
{
return 1;
}
else
{
return PartId.CompareTo(comparePart.PartId);
}
}
}
多权重排序:现根据PartId排序,如果相等,再根据PartName排序
public class Part : IComparable<Part>
{
public int PartId { get; set; }
public string PartName { get; set; }
public override string ToString()
{
return $"ID: {PartId}\t{PartName}";
}
public int CompareTo(Part comparePart)
{
if (comparePart == null)
{
return 1;
}
int ret = this.PartId.CompareTo(comparePart.PartId);
if (ret == 0)
{
return this.PartName.CompareTo(comparePart.PartName);
}
return ret;
}
}
然后调用排序:
List<Part> parts = new List<Part>();
...
parts.Sort(); //升序
lambda表达式排序
using System.Linq;
parts = parts.OrderBy(p => p.PartId).ToList(); //升序
多权重排序
using System.Linq;
parts = parts.OrderBy(p => p.PartId).ThenBy(p => p.PartName).ToList();
附:
详细代码:Github
网友评论