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

Problem with sorting a generic List
Henry Ma
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
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.
Thank you for your help.