如何根据C#.NET Silverlight中字典中键中的值对字典列表进行排序

本文关键字:字典 列表 排序 NET Silverlight 何根 | 更新日期: 2023-09-27 18:27:16

所以我有一个Dictionary<string, string> dictList,我想按字母顺序将Listdict["Title"]值中排序。

我该怎么做?

如果我想取dict["Title"]的值,将其修改为string title = dict["Title"] + "xyz";,然后使用修改后的title作为该dict的排序值(而不实际更改dict["Title"])。。。

我该怎么做呢?

谢谢。

如何根据C#.NET Silverlight中字典中键中的值对字典列表进行排序

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

你似乎想说这样的话:

List<Dictionary<string, string>> list;

你想做的是类似的事情

list.Sort();

但不完全是这样。因此,您可以为Dictionary<string, string>创建一个包装类,然后重载比较方法,或者您可以创建一个类似的比较方法

static int CompareDicts(Dictionary<string, string> x, Dictionary<string, string> y) {
  return String.Compare(x["Title"],y["Title"]);
}

static int CompareDicts(Dictionary<string, string> x, Dictionary<string, string> y) {
  return String.Compare(x["Title"]+"xyz",y["Title"]+"xyz");
}

然后对进行排序

list.Sort(CompareDicts);

编辑:对于列表上的一堆排序函数,请查看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就是这里的解决方案。

dictionary.OrderBy(o => o.Key)
dictionary.OrderByDescending(o => o.Key)

对于修改后的

dictionary.OrderBy(o => o.Key + "xyz")
dictionary.OrderByDescending(o => o.Key + "xyz")