我有一個Dictionary<string, List<Object>>
。我遍歷字典的鍵並顯示按鍵分組的值。我知道SortedDictionary和OrderedDictionary,但是如何按預定義的順序對字典進行排序,而不是按字母順序升序/降序排列?C#按任意順序遍歷字典
假設我知道在我的字典中的所有可能的密鑰將在下面的列表中存在,並希望詞典以下順序進行排序:
- 快速
- 布朗
- 福克斯
- 跳躍
- 超過
我該如何克服o關於這樣做?
我有一個Dictionary<string, List<Object>>
。我遍歷字典的鍵並顯示按鍵分組的值。我知道SortedDictionary和OrderedDictionary,但是如何按預定義的順序對字典進行排序,而不是按字母順序升序/降序排列?C#按任意順序遍歷字典
假設我知道在我的字典中的所有可能的密鑰將在下面的列表中存在,並希望詞典以下順序進行排序:
我該如何克服o關於這樣做?
根本沒有排序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
}
只是一個想法。你可以添加一個「SortKey」屬性到你的對象&使用LINQ來獲得一個排序列表?
如果你想總是訪問從你需要實現IComparer<string>
並傳遞給你的字典構造一個SortedDictionary
的順序和收益的鍵/值對。實現它的最簡單的方法是在你想要的順序串的靜態數組,然後比較兩個字符串的指標:
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());
如果你想保留一個用於其他目的的正常字典(快速查找等),但只是偶爾排序鍵然後使用Linq,因爲Jon建議可能會更好整體。
一種選擇是迭代鍵列表並訪問字典中的值。
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.
}
}
請注意,這不會給你任何詞典中沒有列表中相應鍵的條目。如果列表有重複,它也可能會給你兩次輸入。
您可以使用'SortedDictionary <字符串,列表
時提供'IComparer'沒有任何邏輯可以爲您提供該順序。無論你如何實施它,你都必須自己挑選訂單。 –
Jonesopolis
排序和任意順序是互斥的。 「排序」意味着滿足對象之間的某些關係。排序是重新排序容器中的對象以符合這些條件。 – luk32