2013-01-19 38 views
0

我有一個矩形數組,我想按大小以降序排列。然後,我想選擇前10位,並在另一個採用矩形數組的函數中使用它。以下是我的代碼。但是,當我轉換回數組時,我得到了「至少有一個對象必須實現IComparable」的說法。有人可以指導我嗎?按尺寸排列矩形數組

Rectangle[] BoundingBoxes = GetRectangles(param1, param2); 
IEnumerable<Rectangle> BoundingBoxesSorted = BoundingBoxes.OrderByDescending(
               item => item.Size).Take(10); 

Rectangle[] BoundingBoxes10 = BoundingBoxesSorted.Cast<Rectangle>().ToArray(); 
+3

「BoundingBoxes」是什麼類型? –

+1

Sid顯示與您所問的問題相關的所有代碼..這將有助於解決其他人可能遇到的許多問題..顯示BoundingBoxes的定義方式和方式。 – MethodMan

回答

5

這是因爲System.Drawing.Size(的Rectangle.Size類型)沒有實現IComparable。這是有道理的,因爲沒有自然排序爲一個數字元組,如(Width, Height)(10, 5)將小於(7, 8)

要麼選擇可比較的東西(例如,只是Width或區域Width * Height),要麼傳遞一個自定義的IComparer作爲第二個參數。

+0

感謝Mattias。說得通。 – Sid

4
IEnumerable<Rectangle> BoundingBoxesSorted = 
            BoundingBoxes.OrderBy(r => r.Width * r.Height); 

,也可以定義自定義比較

var comparer = Comparer<Size>.Create((s1, s2) => 
          (s1.Width * s1.Height).CompareTo(s2.Width * s2.Height)); 

IEnumerable<Rectangle> BoundingBoxesSorted = 
             BoundingBoxes.OrderBy(r => r.Size,comparer); 
1

您無法按大小訂購,因爲它不具有可比性。您可能要按區域(寬度*高度)排序。

試試這個:

var top10 = BoundingBoxes 
    .OrderByDescending(b => b.Width * b.Height) 
    .Take(10) 
    .ToArray(); 

注意,您不必Cast,因爲枚舉已經與Rectangles處理。

您還可以擴展Rectangle擁有Area屬性。

public static class Extensions 
{ 
    public static int Area(this Rectangle r) 
    { 
     return r.Width * r.Height; 
    } 
}