方法一: 使用Comparison<T>委托
sort():说明:
如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。要实现这一点,首先应把数组的元素都转换成字符串(如有必要),以便进行比较。
如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下: 若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。 若 a 等于 b,则返回 0。 (此时不排序) 若 a 大于 b,则返回一个大于 0 的值。
//1.读取配置文件中生产列表的相关信息
List<ProductListInfo> proList = new List<ProductListInfo>();
proList.Add(new ProductListInfo
{
WindingNumber = Convert.ToDouble(coilBreakPointData.WindingNumber),
Separator = ":",
ProductInfo = coilBreakPointData.InfoText
});
//1.5按照线圈匝数升序排列
Comparison<ProductListInfo> comparison = new Comparison<ProductListInfo>
(
(ProductListInfo x, ProductListInfo y) =>{
if (x.WindingNumber < y.WindingNumber) return -1;
else if (x.WindingNumber == y.WindingNumber) return 0;
else return 1;}
);
proList.Sort(comparison);
方法二: Lambda表达式使用Comparison委托
// Lambda表达式实现Comparison委托
//例一:
peopleList.Sort((p1, p2) =>
{
if (p1.Name != p2.Name)
{
return p2.Name.CompareTo(p1.Name);
}
else if (p1.Age != p2.Age)
{
return p2.Age.CompareTo(p1.Age);
}
else return 0;
});
//例二:
List<ShapeInfo> shapeInfos = DrawManager.getShapeInfos(shapeCombs);
shapeInfos.Sort(delegate (ShapeInfo S1, ShapeInfo S2)
{
return S1.currentShape.getArea().CompareTo(S2.currentShape.getArea());
});
// 方法2 使用IComparer<T>接口 sort(IComparable<T> comparable )。
proList.Sort(new classComparer ());
新建一个动态排序类:
public class classComparer : IComparer<ProductListInfo>
{
public int Compare(ProductListInfo left, ProductListInfo right)
{
if (left.WindingNumber > right.WindingNumber )
return 1;
else if (left.WindingNumber == right.WindingNumber )
return 0;
else
return -1;
}
};
// 方法3 除以上两种方法以外还可以使用另一种方法,在ProductListInfo类中实现IComparable<T>
proList.Sort();
public class ProductListInfo : IComparable<ProductListInfo>
{
public double WindingNumber { get; set; }
public string ProductInfo { get; set; }
public string Separator { get; set; }
public int CompareTo(ProductListInfo other)
{
if (this.WindingNumber > other.WindingNumber )
return 1;
else if (this.WindingNumber == other.WindingNumber )
return 0;
else
return -1;
}
}