2011-09-19 32 views
1

有谁知道如何排序不同类型的结构列表(示例代码如下)?网络中不同类型的结构的排序列表2.0

我们目前使用的是Net 2.0,所以我们不能使用Linq。

在此先感谢!

public struct dataKeys 
    { 
     private long key1; 
     private long key2; 
     private string key3; 

     public long Key1; 
     { 
      get { return key1;} 
      set { key1 = value; } 
     } 
     public long Key2; 
     { 
      get { return key2;} 
      set { key2 = value; } 
     } 
     public string Key3; 
     { 
      get { return key3;} 
      set { key3 = value; } 
     } 
    } 

    . . . 

    List<dataKeys> dataKeyList = new List<dataKeys>(); 

    // tried this but will only work for one 
    // dataKeyList.Sort((s1, s2) => s1.Key1.CompareTo(s2.Key1)); 

喜欢的东西:

FROM: 
2, 2, C 
1, 1, A 
1, 3, A 
3, 1, B 
1, 2, B 
2, 1, A 
2, 3, A 
1, 2, A 

TO: 
1, 1, A 
1, 2, A 
1, 2, B 
1, 3, A 
2, 1, A 
2, 2, C 
2, 3, A 
3, 1, B 
+1

重新 “我们目前正在使用.NET 2.0,所以我们不能使用Linq。” - 是LINQBridge的一个选项? –

回答

3
dataKeyList.Sort((s1, s2) => { 
    int result = s1.Key1.CompareTo(s2.Key1); 
    if(result == 0) { 
     result = s1.Key2.CompareTo(s2.Key2); 
     if(result == 0) { 
      result = s1.Key3.CompareTo(s2.Key3); 
     } 
    } 
    return result; 
}); 

或者编写自定义比较(IComparer<dataKeys>),或有dataKeys实现IComparable<dataKeys>

+0

除了在分号前删除多余的括号外,这个工作!谢谢,Marc! –

+0

@niki - oops;修正了括号提示,谢谢Joe, –