I am doing it in C#
.net2.0
I am having a list which contains two strings and i want to sort it.
list is like List<KeyValuePair<string,string>>
I have to sort it according to the first string
, which is:
I tried to use Sort()
, but it gives me the exception: "Invalid operation exception","Failed to compare two elements in array".
Can you suggest me anyway in which I can do this?
As you are stuck with .NET 2.0, you will have to create a class that implements IComparer<KeyValuePair<string, string>>
and pass an instance of it to the Sort
method:
public class KvpKeyComparer<TKey, TValue> : IComparer<KeyValuePair<TKey, TValue>>
where TKey : IComparable
{
public int Compare(KeyValuePair<TKey, TValue> x,
KeyValuePair<TKey, TValue> y)
{
if(x.Key == null)
{
if(y.Key == null)
return 0;
return -1;
}
if(y.Key == null)
return 1;
return x.Key.CompareTo(y.Key);
}
}
list.Sort(new KvpKeyComparer<string, string>());
If you would use a newer version of the .NET framework, you could use LINQ:
list = list.OrderBy(x => x.Key).ToList();
Why not use a SortedDictionary instead?
Here's the MSDN article on it:
http://msdn.microsoft.com/en-us/library/f7fta44c(v=vs.80).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With