2012-09-10 2 views
1

어떻게 지역별로 사각형 목록을 정렬합니까? MSDN 라이브러리에서에서 IComparable으로 찾고, 그러나 그것을 알아낼 수 없습니다 ... 나는이 쓴 :정렬 목록 <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);}} 

을 그리고 ...

그것은 작동하지만, 꽤 추한, 나는 더 쉬운 방법이 알고 당신은 LINQ를 사용할 수 있습니다 가정

답변

2

이것에 대해, 람다 식을 사용하여 자신 만의 비교자를 생성하는 방법

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

좋아! 람다는'비교 '대리자를 만듭니다. –

6

,이 같은 작동한다고 :

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를 비교하는 것

의미있는 예와 함께 눈에 띄지 않게 분명하다. 나는 technobabble을 먼저 읽었고, 정말로 복잡하게 들렸다. :(당신의 Rectangle 클래스에이 방법을 추가

+0

어? 위의 경우 CompareByArea (r1, r2) == 1) && (CompareByArea (r2, r1) == 1)가 두 번 전달 된 경우에도 true가 될 수 없습니다. –

1

봅니다 :. 당신이 지역에서 두 개의 사각형을 비교할 수 있도록해야

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는 지역에 따라 즉, 올바르게 자체를 정렬해야합니다. 당신은 모든 것을 따라 할 수 있도록 IComparable에서 Rectangle을 유도 할 필요가있다.