Problem with sorting a generic List

The new generics in C# 2.0 are really breath taking, but I've got some problems with sorting a Generic List.

I've got a List<KeyValueType<TKey, TValue>>, so this is a list containing another generic type. Now I would like to sort this list by the TKey type of the KeyValueType<TKey, TValue> type. The list contains KeyValueType objects with in which the TKey is unique.

I've been working on it all night, but can't get the syntax right. I tried to write a class that implements the IComparer<KeyValueType<TKey, TValue>> interface, but the compiler reports errors in my code.

How should this be written


PS. here is some incorrect code that maybe clarifies what I'm doing:


    public class BinTree
    {
        public void AddToTree(List<KeyValuePair<TKey, TValue>> myList)
        {
            Sort the List so it can be added to the tree in a balanced way
            myList.Sort( new MyComparer<KeyValuePair<TKey, TValue>>() );

            code to add to tree here.
        }
    }

    Compiler Error CS0081: Type parameter declaration must be an identifier not a type.
    public class MyComparer<KeyValuePair<TKey, TValue>>
        where TKey : IComparer<KeyValuePair<TKey, TValue>>, IComparable<TKey>
    {
        #region IComparer<KeyValuePair<TKey,TValue>> Members

        public int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
        {
            return x.Key.CompareTo(y.Key);
        }

        #endregion
    }

 



Answer this question

Problem with sorting a generic List

  • Henry Ma

    Tongue Tied

    Hmmm, MAYBE you're trying to do this...



    public class BinTree<K,V>
    {
       public void AddToTree(List<KeyValuePair<K,V>> myList)
       {
       }
    }

    public class MyComparer<K,V> : IComparer<KeyValuePair<K,V>>
    {
       public int Compare( KeyValuePair<K,V> x, KeyValuePair<K,V> y)
       {
       }
    }

     


  • patlora

    Almost, but the problem here is that I still can't compare the <K> type objects with the CompareTo() function. But using your example the real solution is easily found. The only thing we now need is the IComparable interface on the <K> type, so: "where K: IComparable<K>".



        public class KeyValuePairComparer<K, V> : IComparer<KeyValuePair<K, V>>
            where K: IComparable<K>
        {
            public int Compare(KeyValuePair<K, V> x, KeyValuePair<K, V> y)
            {
                return x.Key.CompareTo(y.Key);
            }
        }

     


    It is so simple that I still wonder why I didn't see this before. Tongue Tied

    Thank you for your help.

  • Problem with sorting a generic List