2011-04-19 7 views
0

개체와 속성을 가진 arraylist가 있습니다. 객체의 속성을 비교하는 방법이 있습니까?Array 목록의 개체 비교

업데이트 다음은 IComparer 인터페이스를 구현하는 새로운 클래스를 작성 목록 예

listTA = {(ID, MonAry[], RequestDate), (ID, MonAry[], RequestDate)}; 
+0

예를 사용하여 하나의 튜토리얼 블로그를 확인하지만, 몇 가지 예를 들어 데이터 (입력 및 comparation의 바람직한 결과) –

+0

예를 제공하십시오. (귀하의 질문은 너무 모호합니다. 내가 물어 보려는 내용에 대한 추측조차 가지고 있지 않습니다.) –

+0

정렬하려고합니까? –

답변

2

입니다. 다음 myList.Sort(new MyComparer());를 호출하여 목록을 정렬 할 수 있습니다 당신은 새로운 MyComparer().Compare(firstOne, secondOne);

샘플을 사용하여 다른 하나는 각 하나를 비교할 수 있습니다

using System; 
using System.Collections; 

public class SamplesArrayList { 

    public class myReverserClass : IComparer { 

     // Calls CaseInsensitiveComparer.Compare with the parameters reversed. 
     int IComparer.Compare(Object x, Object y) { 
      // you can implement this method as you wish! cast your x and y objects and access to their properties. 
      return((new CaseInsensitiveComparer()).Compare(y, x)); 
     } 

    } 

    public static void Main() { 

     // Creates and initializes a new ArrayList. 
     ArrayList myAL = new ArrayList(); 
     myAL.Add("The"); 
     myAL.Add("quick"); 
     myAL.Add("brown"); 
     myAL.Add("fox"); 
     myAL.Add("jumps"); 
     myAL.Add("over"); 
     myAL.Add("the"); 
     myAL.Add("lazy"); 
     myAL.Add("dog"); 

     // Displays the values of the ArrayList. 
     Console.WriteLine("The ArrayList initially contains the following values:"); 
     PrintIndexAndValues(myAL); 

     // Sorts the values of the ArrayList using the default comparer. 
     myAL.Sort(); 
     Console.WriteLine("After sorting with the default comparer:"); 
     PrintIndexAndValues(myAL); 

     // Sorts the values of the ArrayList using the reverse case-insensitive comparer. 
     IComparer myComparer = new myReverserClass(); 
     myAL.Sort(myComparer); 
     Console.WriteLine("After sorting with the reverse case-insensitive comparer:"); 
     PrintIndexAndValues(myAL); 

    } 

    public static void PrintIndexAndValues(IEnumerable myList) { 
     int i = 0; 
     foreach (Object obj in myList) 
     Console.WriteLine("\t[{0}]:\t{1}", i++, obj); 
     Console.WriteLine(); 
    } 

} 

다른 IComparer 샘플 :

private class sortYearAscendingHelper : IComparer 
{ 
    int IComparer.Compare(object a, object b) 
    { 
     car c1=(car)a; 
     car c2=(car)b; 
     if (c1.year > c2.year) 
     return 1; 
     if (c1.year < c2.year) 
     return -1; 
     else 
     return 0; 
    } 
} 
+1

+1 OP가 정렬을 위해 비교를 필요로한다면, 이것은 훌륭한 대답입니다. :) – jsmith

+0

배열 (MonAry [])의 값을 다른 객체의 MonAry []와 비교하려면 어떻게해야합니까? –