基本上,我在C#中有一个完整的结构列表,看起来像这样(代码可能不合适语法)
public struct Numbers {
public int DistanceFromArbitraryPoint;
public int X;
public int Y;
}
我想做的是对列表进行排序:
结果将成为:
Distance 12, x 0, y 0;
Distance 4, x 20, y 20;
Distance 6, x 0, y 3;
第一步之后:
Distance 4, x 20, y 20;
Distance 6, x 0, y 3;
Distance 12, x 0, y 0;
在步骤2之后(如果距离<10,则按X和Y的总和进行排序)
Distance 6, x 0, y 3; // lower X and Y Sum, goes first
Distance 4, x 20, y 20;
Distance 12, x 0, y 0; // Distance higher than 10, remains unsorted
答案 0 :(得分:2)
这里需要更复杂的比较方法
var numbers = new List<Numbers>{ new Numbers(6,0,3), new Numbers(12,0,0),
new Numbers(4,20,20), new Numbers(5,20,20)};
int d = 10;
numbers.Sort((a,b)=>
{
if (a.DistanceFromArbitraryPoint >= d && b.DistanceFromArbitraryPoint >= d)
return a.DistanceFromArbitraryPoint.CompareTo(b.DistanceFromArbitraryPoint);
if (a.DistanceFromArbitraryPoint >= d)
return 1;
if (b.DistanceFromArbitraryPoint >= d)
return -1;
int c = (a.X+a.Y).CompareTo(b.X+b.Y);
if (c == 0)
c = a.DistanceFromArbitraryPoint.CompareTo(b.DistanceFromArbitraryPoint);
return c;
});
输出:
6 (0,3); 4 (20,20); 5 (20,20); 12 (0,0)
使用来自Sort(Comparison<T> comparison)
的 List<T>
,而不是Linq
public struct Numbers
{
public Numbers(int d, int x, int y)
{
DistanceFromArbitraryPoint = d;
X = x;
Y = y;
}
public int DistanceFromArbitraryPoint;
public int X;
public int Y;
public override string ToString()
{
return String.Format("{0} ({1},{2})", DistanceFromArbitraryPoint, X,Y);
}
}