c# - SortedDictionary 按键的相反顺序

标签 c# linq reverse sorteddictionary

<分区>

我有以下字典:

SortedDictionary<int, string> dictionary = new SortedDictionary<int, string>();
dictionary.add(2007, "test1");
dictionary.add(2008, "test2");
dictionary.add(2009, "test3");
dictionary.add(2010, "test4");
dictionary.add(2011, "test5");
dictionary.add(2012, "test6");

我想颠倒元素的顺序,这样当我在屏幕上显示项目时,我可以从 2012 开始。如果可能的话,我想将颠倒的字典重新分配回可变字典。

我尝试了 dictionary.Reverse,但似乎没有我想象的那么容易。

最佳答案

如果您使用的是最新版本的框架,.NET 4.5 (Visual Studio 2012),您可以使用 Comparer<>.Create 轻松完成。 .是这样的:

var dictionary =
  new SortedDictionary<int, string>(Comparer<int>.Create((x, y) => y.CompareTo(x)));

注意x的顺序和 y在 lambda 中。

关于c# - SortedDictionary 按键的相反顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323267/

相关文章:

arrays - 在不创建新数组的情况下反转字符数组

c++ - 试图反转一个字符串

c# - 在没有 OWIN 的情况下使用 Microsoft Identity 的示例

c# - 当 ASP.net MVC Razor 中的其他属性相同时重构循环以合并一个属性

c# - 在 C# 中调整 ComboBox DropDown 宽度

xml - 如何按属性值对 LINQ C# 中的 XML 进行排序?还有MVC

c# - 处理后SqlDataReader记录的使用

c# - SQLite插入数据到表后如何获取最后一行ID

C# - 从 DataTable 中删除具有相同列值的行

ruby - 这种迭代反向方法在 Ruby 中如何工作?