1

長方形のリストを面積でソートするにはどうすればよいですか? 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);}}

それは機能しますが、かなり醜いです。もっと簡単な方法があることは知っています...

4

4 に答える 4

6

LINQを使用できると仮定すると、次のようなものが機能するはずです。

var sortedList = Oblici.OrderBy(r => r.Width * r.Height).ToList();
于 2012-09-10T21:40:08.920 に答える
2

これはどうですか、ラムダ式を使用して独自のComparerを作成します

mylist.Sort((X, Y) => ((X.Height * X.Width).CompareTo(Y.Height * Y.Width)));
于 2012-09-10T21:43:06.143 に答える
1

そして、これは、他の 2 つを取得するのに役立つ長いバージョンです。

何かのようなもの

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 の比較子は、何らかの方法で 2 つの T を比較して -1,0,1 (慣例により小さい、等しい、または大きい) を返す静的 (通常) 関数です。

意味のある例でイライラするほど明白ですよね。私も最初にテクノバブルを読みましたが、とても複雑に聞こえました。:(

于 2012-09-10T21:53:57.383 に答える
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");
}

これにより、2 つの長方形を面積で比較できるようになります。

SortedListofRectangleは、それ自体を正しく、つまり領域別にソートする必要があります。Rectangleすべてが従うようにするには、から派生させる必要がありますIComparable

于 2012-09-10T21:54:20.247 に答える