我在面试中被问到以下问题。如何按数组列表中的顺序按键对字典进行排序。
例如我有一个字典如下
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/