2012-09-10 55 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,以使所有內容都遵循。