2012-09-10 58 views
1

如何按其区域排列矩形列表?在寻找到了IComparable在MSDN库,但不能看着办吧......我写了这个:排序列表<Rectangle>

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);}} 

和它的作品,但它是很丑陋的,我知道有一个更简单的方法...

回答

2

这个怎么样,使用lambda表达式来创建自己的Comparer

mylist.Sort((X, Y) => ((X.Height * X.Width).CompareTo(Y.Height * Y.Width))); 
+0

好!lambda创建了一个'Comparison '委托。 –

6

假设你可以使用LINQ,这样的事情应该工作:

var sortedList = Oblici.OrderBy(r => r.Width * r.Height).ToList(); 
1

这里是漫长的版本,将帮助你获得另外两个。

喜欢的东西

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) 

一种用于列表的比较器是一个静态返回-1,0,1(小于(通常)函数,等于或大于约定)从某种程度上比较两个Ts

对于一个有意义的例子来说,刺激性很明显是不是。我也首先阅读了技术可能性,听起来很复杂。 :(

+0

呃?即使它传递了两次(CompareByArea(r1,r2)== 1)&&(CompareByArea(r2,r1)== 1)在上面也不会是真的。 –

1

尝试增加这个方法将你Rectangle类:

public int CompareTo(object obj) 
{ 
    if (obj == null) return 1; 

    Rectangle otherRectangle = obj as Rectangle; 

    if (otherRectangle != null) 
    return this.Width * this.Height - obj.Width * obj.Height; 
    else 
    throw new ArgumentException("Object is not a Rectangle"); 
} 

这应该允许您按面积两个矩形比较

Rectangle一个SortedList本身应该正确地排序,按面积IE浏览器。您需要从IComparable推导出Rectangle,以使所有内容都遵循。