2011-04-19 145 views
0

我有一个包含对象及其属性的数组列表。有没有办法比较对象的属性?比较数组列表中的对象

更新下面列表例如

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

是的,但请提供一些示例数据(输入及比理想的结果) – 2011-04-19 18:20:39

+0

是。 (你的问题太模糊了我什至不知道你想问什么) – 2011-04-19 18:20:46

+0

你想排序吗? – 2011-04-19 18:20:55

回答

2

创建一个新的类中实现IComparer接口。那么你可以通过调用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 2011-04-19 18:36:57

+0

如果我想将数组内的值(MonAry [])与另一个对象的MonAry []进行比较,我应该怎么做? – 2011-04-20 08:25:56