use*_*390 5 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");
Run Code Online (Sandbox Code Playgroud)
和一个数组列表如下
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");
Run Code Online (Sandbox Code Playgroud)
如何按照它在数组列表中的顺序对字典进行排序?
好吧,您无法对字典本身进行排序,但您可以将键值对提取为列表并对它们进行排序:
IEnumerable<KeyValuePair<string, string>> pairs =
stringDict.OrderBy(kvp => stringArList.IndexOf(kvp.Key));
Run Code Online (Sandbox Code Playgroud)
但是没有办法以任何特定顺序“遍历”字典项。
您可以创建一个SortedDictionary并提供一个IComparer<string>
var d = new SortedDictionary<string, string>(stringDict,
new PositionComparer(stringArList));
Run Code Online (Sandbox Code Playgroud)
实施方式为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));
}
}
Run Code Online (Sandbox Code Playgroud)