[英]C# iterating over Dictionary by arbitrary order
我有一個Dictionary<string, List<Object>>
。 我遍歷字典的鍵並顯示按鍵分組的值。 我知道SortedDictionary和OrderedDictionary,但是如何按照預定義的順序對字典進行排序,而不僅是按字母順序進行升/降序?
假設我知道字典中所有可能的鍵都將存在於以下列表中,並希望按以下順序對字典進行排序:
我該怎么做呢?
您根本不需要對Dictionary<,>
進行排序。 但是,如果要按特定順序遍歷條目(或鍵),則可以使用LINQ的OrderBy
並以該順序遍歷一組已知的值,就可以在其他位置進行有序的遍歷。 例如:
string[] orderedKeys = { "Quick", "Brown", "Fox", "Jumped", "Over" };
var orderedPairs = dictionary.OrderBy(pair => orderedKeys.IndexOf(pair.Key));
foreach (var pair in orderedPairs)
{
// Use pair.Key and pair.Value here
}
如果要始終按該順序訪問鍵/值對並從SortedDictionary
受益,則需要實現IComparer<string>
並將其傳遞給字典構造函數。 實現它的最簡單方法是按照所需順序具有靜態字符串數組,然后比較兩個字符串的索引:
public class MyStringComparer : IComparer<string>
{
static string[] StringsInOrder = new [] { "Quick", "Brown", "Fox", "Jumped", "Over" };
public int Compare(string s1, string s2)
{
// find the indexes of the strings in the desired sort order
int i1 = Array.IndexOf(StringsInOrder, s1);
int i2 = Array.IndexOf(StringsInOrder, s2);
if(i1 < 0)
// put at the end in alpha order
if(i2 < 0)
return s1.CompareTo(s2);
else
// send s1 to the end
return 1;
else
if(i2 < 0)
// send s2 to the end
return -1;
else
// compare the indices in the array
return i1.CompareTo(i2);
}
}
用法:
var d = new SortedDictionary<string, string> (new MyStringComparer());
如果您想保留普通詞典用於其他目的(快速查找等),但偶爾對鍵進行排序,則按Jon的建議使用Linq可能總體上更好。
只是一個想法。 您可以將“ SortKey”屬性添加到對象並使用LINQ獲取排序列表嗎?
一種選擇是迭代鍵列表並訪問字典中的值。
string[] orderedKeys = { "Quick", "Brown", "Fox", "Jumped", "Over" };
foreach (var key in orderedKeys)
{
List<object> values;
if (dictionary.TryGetValue(key, out values))
{
// Here you have the key and the list of values
}
else
{
// The key was not in the dictionary.
}
}
請注意,這不會給您字典中沒有列表中相應鍵的任何條目。 如果列表重復,它也可能會給您兩次輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.