Sort list <keyValuePair <string, string >>
I am doing this in C#
.net2.0
I have a list that contains two lines and I want to sort it. the list is likeList<KeyValuePair<string,string>>
I need to sort it according to the first one string
, which:
- ACC
- Abla
- SUD
- FLO
- IHNJ
I tried to use Sort()
, but it gives me an exception: "Invalid operation exception", "Failed to compare two elements in the array."
Can you suggest me so I can do this?
source to share
Since you're stuck with .NET 2.0, you need to create a class that implements IComparer<KeyValuePair<string, string>>
and pass an instance of it to the method Sort
:
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 are using a newer version of the .NET framework, you can use LINQ:
list = list.OrderBy(x => x.Key).ToList();
source to share
Why not use SortedDictionary instead?
Here's an MSDN article on it:
http://msdn.microsoft.com/en-us/library/f7fta44c(v=vs.80).aspx
source to share
You can just use a generic delegate Comparison<T>
. Then you avoid having to define the class just for the implementation IComparer<T>
, but just need to make sure that you define your method according to the signature of the delegate.
private int CompareByKey(KeyValuePair<string, string>, KeyValuePair<string, string> y)
{
if (x.Key == null & y.Key == null) return 0;
if (x.Key == null) return -1;
if (y.Key == null) return 1;
return x.Key.CompareTo(y.Key);
}
list.Sort(CompareByKey);
source to share
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();
pairs.Add(new KeyValuePair<string, string>("Vilnius", "Algirdas"));
pairs.Add(new KeyValuePair<string, string>("Trakai", "Kestutis"));
pairs.Sort(delegate (KeyValuePair<String, String> x, KeyValuePair<String, String> y) { return x.Key.CompareTo(y.Key); });
foreach (var pair in pairs)
Console.WriteLine(pair);
Console.ReadKey();
source to share