如何按面积对矩形列表进行排序?我已经在msdn库中查找了IComparable,但无法找到它...我写了以下内容:
SortedL= new List<Rectangle>();
int count1 = 0;
int count3 = redovi;
while (count1 < count3)
{
int count2 = 0;
while (count2 < count3)
{
int x = Oblici[count1].Width;
int y = Oblici[count1].Height;
int z = Oblici[count2].Width;
int w = Oblici[count2].Height;
int area1 = x * y;
int area2 = z * w;
int a = area1.CompareTo(area2);
if (a < 0)
{
count1 = count2;
if (count2 < (count3 - 1))
{
count2++;
}
else break;
}
else if (a == 0)
{
if (count2 < (count3 - 1))
{
count2++;
}
else break;
}
else if (a > 0)
{
if (count2 < count3 - 1)
{
count2++;
}
else break;
}
}
SortedL.Add(Oblici[count1]);
Oblici.RemoveAt(count1);
count3 = (count3 - 1);}}它是有效的,但它相当丑陋,而且我知道有一种更简单的方法...
发布于 2012-09-11 05:43:06
如何,使用lambda表达式创建自己的比较器
mylist.Sort((X, Y) => ((X.Height * X.Width).CompareTo(Y.Height * Y.Width)));发布于 2012-09-11 05:40:09
假设你可以使用LINQ,这样的东西应该可以工作:
var sortedList = Oblici.OrderBy(r => r.Width * r.Height).ToList();发布于 2012-09-11 05:53:57
这里是长篇大论的版本,它将帮助您获得其他两个版本。
就像这样
private static int CompareByArea(Rectangle r1, Rectangle r2)
{
int a1 = r1.Width * r1.Height;
int a2 = r2.Width * r2.Height;
if (a1 < a2)
{
return - 1;
}
else
{
if (a1 > a2)
{
return 1;
}
}
return 0;
}然后
MyList.Sort(CompareByArea)List的比较器是一个静态(通常)函数,它以某种方式通过比较两个t返回-1,0,1 (小于、等于或大于
一个有意义的例子明显得让人恼火,不是吗?我也先读了技术术语,听起来很复杂。:(
https://stackoverflow.com/questions/12359839
复制相似问题