So I have a List
of Dictionary<string, string> dict
and I want to sort the List
alphabetically off the dict["Title"]
value.
How do I go about doing that?
And, what if I want to take the value of dict["Title"]
, modify it as string title = dict["Title"] + "xyz";
, and then use the modified title
as the sorting value of that dict
(without actually changing dict["Title"]
)...
How would I go about doing that as well?
Thanks.
Linq it:
var dicts = new List<Dictionary<string, string>>();
var sort = dicts.OrderBy(x => x.ContainsKey("Title") ? x["Title"] : string.Empty);
var sort2 = dicts.OrderBy(x => x.ContainsKey("Title") ? x["Title"] + "xyz" : string.Empty);
It seems like you are trying to say something like this:
List<Dictionary<string, string>> list;
And what you want to do is something like
list.Sort();
But not quite. So, what you can do instead is either make a wrapper class for Dictionary<string, string>
and then overload the compare methods, or you could 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 to sort
list.Sort(CompareDicts);
Edit: For a bunch of Sort functions on a List, check out http://msdn.microsoft.com/en-us/library/3da4abas.aspx
var dicts = new List<Dictionary<string, string>>();
// populate dictionaries.
var sorted = dicts.OrderBy(x => x.ContainsKey("Title") ? x["Title"] : string.Empty));
LINQ is the solution here.
dictionary.OrderBy(o => o.Key)
dictionary.OrderByDescending(o => o.Key)
And for the modified version
dictionary.OrderBy(o => o.Key + "xyz")
dictionary.OrderByDescending(o => o.Key + "xyz")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.