按值(而非键)顺序对 StringDictionary 进行排序(或迭代)的“最佳”方法是什么
例如键-值
- 1 - X 标签
- 2 - 一个标签
- 3 - 其他标签
会给
- 2 - 一个标签
- 3 - 其他标签
- 1 - X 标签
编辑 - 我的意思是说“使用 .NET 2.0 功能”。对不起,我不好...
最佳答案
使用 LINQ:
var items = from k in d.Keys
orderby d[k] ascending
select k;
如果您受限于 C# 2.0 功能,请使用:
IDictionary<string, string> d = new Dictionary<string, string>();
d["1"] = "X label";
d["2"] = "A label";
d["3"] = "Other Label";
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(d);
myList.Sort(
delegate(KeyValuePair<string, string> a,
KeyValuePair<string, string> b)
{
return a.Value.CompareTo(b.Value);
}
);
注意: 如果您使用的是 StringDictionary 而不是 Dictionary,请查看 Anthony 的解决方案。
关于c# 按值而不是键对 StringDictionary 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3335902/