c# - 按 Arraylist 中的顺序按键对字典进行排序

标签 c# dictionary arraylist

我在面试中被问到以下问题。如何按数组列表中的顺序按键对字典进行排序。

例如我有一个字典如下

Dictionary<string, string> stringDict = new Dictionary<string, string>();

stringDict.Add("1", "One");
stringDict.Add("7", "Seven");
stringDict.Add("6", "Six");
stringDict.Add("2", "Two");
stringDict.Add("3", "Three");
stringDict.Add("5", "Five");
stringDict.Add("4", "Four");

和一个数组列表如下

ArrayList stringArList = new ArrayList();

stringArList.Add("1");
stringArList.Add("2");
stringArList.Add("3");
stringArList.Add("5");
stringArList.Add("6");
stringArList.Add("7");
stringArList.Add("4");

如何按照字典在数组列表中的顺序对字典进行排序?

最佳答案

你不能对字典本身进行排序,但是你可以提取键值对作为列表并对那些进行排序:

IEnumerable<KeyValuePair<string, string>> pairs = 
    stringDict.OrderBy(kvp => stringArList.IndexOf(kvp.Key));

但是没有办法以任何特定顺序“遍历”字典项目。

您可以创建一个 SortedDictionary并提供 IComparer<string>

var d = new SortedDictionary<string, string>(stringDict, 
                                        new PositionComparer(stringArList));

随着 Comparer实现为:

public class PositionComparer : IComparer<string>
{
   private ArrayList Keys {get; set;}

   public PositionComparer(ArrayList keys)
   {
       Keys = keys;
   }

   public int Compare(string s1, string s2)
   {
       return Keys.IndexOf(s1).CompareTo(Keys.IndexOf(s2));
   }
}

关于c# - 按 Arraylist 中的顺序按键对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23255819/

相关文章:

python - 从字典中的 itemgetter 查找值

python - 如何按字典中的值对字典列表进行排序?

Java:使用 ArrayList 检查 CSV 文件中的重复行

JAVA如何创建一维和多维数组

c# - 对 BiDirection 字典使用集合初始值设定项

java - 数组的 ArrayList 与 ArrayLists 的数组与类似的东西

c# - ContinueWith 和任务的结果

c# - 如何让 EventLog 将用户名记录到 Window 事件日志中?

c# - 如何在屏幕中央显示工具提示?

c# - Delphi 到 .NET + C#