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.

+3


source to share


4 answers


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);

      

+6


source


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

+4


source


var dicts = new List<Dictionary<string, string>>();

// populate dictionaries.

var sorted = dicts.OrderBy(x => x.ContainsKey("Title") ? x["Title"] : string.Empty));

      

0


source


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")

      

-1


source







All Articles