结构体排序(数组)
1 示例 1.1 以PointF为例展示效果 1.2 运行结果展示
2实际运用 2.1 创建结构体 2.2 调用示例 2.3 运行结果展示
1 示例
1.1 以PointF为例展示效果
private void button1_Click ( object sender, EventArgs e)
{
Random random = new Random ( ) ;
List< PointF> list = new List< PointF> ( ) ;
for ( int i = 0 ; i < 10 ; i++ )
{
list. Add ( new PointF ( i, random. Next ( 1 , 100 ) ) ) ;
}
var listSortMaxToMin = list. ToList ( ) ;
listSortMaxToMin. Sort ( CompareMaxToMin) ;
var listSortMinToMax = list. ToList ( ) ;
listSortMaxToMin. Sort ( CompareMinToMax) ;
}
private static int CompareMaxToMin ( PointF p1, PointF p2)
{
if ( p1. Y == p2. Y)
return 0 ;
else if ( p1. Y < p2. Y)
return 1 ;
else
{
return - 1 ;
}
}
private static int CompareMinToMax ( PointF p1, PointF p2)
{
if ( p1. Y == p2. Y)
return 0 ;
else if ( p1. Y < p2. Y)
return 1 ;
else
{
return - 1 ;
}
}
1.2 运行结果展示
2实际运用
2.1 创建结构体
public struct MyPoint
{
public double X;
public double Y;
public MyPoint ( double x, double y)
{
X = x;
Y = y;
}
}
2.2 调用示例
public void GetMostValue ( double [ ] arr1, double [ ] arr2, uint count, out List< MyPoint> result)
{
result = new List< MyPoint> ( ) ;
if ( arr1 == null ) throw new Exception ( "arrX不可为null" ) ;
if ( arr2 == null ) throw new Exception ( "arrY不可为null" ) ;
if ( arr1. Length != arr2. Length) throw new Exception ( "数组arrX和arrY的元素总数不同" ) ;
if ( arr1. Length < count) throw new Exception ( "数组元素数不同不可小于count" ) ;
List< MyPoint> list = new List< MyPoint> ( ) ;
int length = arr1. Length;
for ( int i = 0 ; i < length; i++ )
{
list. Add ( new MyPoint ( arr1[ i] , arr2[ i] ) ) ;
}
list. Sort ( ( p1, p2) =>
{
if ( p1. Y < p2. Y) return 1 ;
if ( p1. Y > p2. Y) return - 1 ;
return 0 ;
} ) ;
for ( int i = 0 ; i < count; i++ )
{
result. Add ( list[ i] ) ;
}
}
2.3 运行结果展示