sort list of struct of different types in net 2.0

2019-08-05 05:08发布

问题:

Does anyone know how to sort a list of struct with different types (sample code below)?

We are currently using Net 2.0, so we cannot use Linq.

Thanks in advance!

    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));

Something like:

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:

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;
});

Or write a custom comparer (IComparer<dataKeys>), or have dataKeys implement IComparable<dataKeys>.



回答2:

Yes, use .Sort with a custom comparison delegate:

http://msdn.microsoft.com/en-us/library/w56d4y5z%28v=VS.80%29.aspx