How to sort a list of dictionaries based on a value in a key in a dictionary in C # .NET Silverlight?
So I have List
of Dictionary<string, string> dict
and I want to sort List
alphabetically from value dict["Title"]
.
How should I do it?
And what if I want to accept a value dict["Title"]
, change it as string title = dict["Title"] + "xyz";
and then use the changed title
as the sort value of that dict
(without actually changing it dict["Title"]
) ...
How should I do it?
Thank.
source to share
You seem to be trying to say something like this:
List<Dictionary<string, string>> list;
And what you want to do is something like
list.Sort();
But not really. So what you can do is either make a wrapper class for Dictionary<string, string>
and then overload the comparison methods, or you can make a comparison method like
static int CompareDicts(Dictionary<string, string> x, Dictionary<string, string> y) {
return String.Compare(x["Title"],y["Title"]);
}
or
static int CompareDicts(Dictionary<string, string> x, Dictionary<string, string> y) {
return String.Compare(x["Title"]+"xyz",y["Title"]+"xyz");
}
And then sort
list.Sort(CompareDicts);
Edit: For a group of sort functions in the list, select http://msdn.microsoft.com/en-us/library/3da4abas.aspx
source to share