手短に言えば、ディクショナリは「キーと値のコレクションを表す」ので、仕方がないということです。これは、いかなる順序付けも意味しません。あなたが見つけたハックはクラスの定義の外にあり、変更される可能性があります。
おそらく、この状況で Dictionary が本当に必要なのか、または KeyValuePairs のリストを使用して問題を解決できるのかをまず自問する必要があります。
それ以外の場合は、次のようなものが役立つ場合があります。
public class IndexableDictionary<T1, T2> : Dictionary<T1, T2>
{
private SortedDictionary<int, T1> _sortedKeys;
public IndexableDictionary()
{
_sortedKeys = new SortedDictionary<int, T1>();
}
public new void Add(T1 key, T2 value)
{
_sortedKeys.Add(_sortedKeys.Count + 1, key);
base.Add(key, value);
}
private IEnumerable<KeyValuePair<T1, T2>> Enumerable()
{
foreach (T1 key in _sortedKeys.Values)
{
yield return new KeyValuePair<T1, T2>(key, this[key]);
}
}
public new IEnumerator<KeyValuePair<T1, T2>> GetEnumerator()
{
return Enumerable().GetEnumerator();
}
public KeyValuePair<T1, T2> this[int index]
{
get
{
return new KeyValuePair<T1, T2> (_sortedKeys[index], base[_sortedKeys[index]]);
}
set
{
_sortedKeys[index] = value.Key;
base[value.Key] = value.Value;
}
}
}
クライアントコードは次のようになります。
static void Main(string[] args)
{
IndexableDictionary<string, string> fooDict = new IndexableDictionary<string, string>();
fooDict.Add("One", "One");
fooDict.Add("Two", "Two");
fooDict.Add("Three", "Three");
// Print One, Two, Three
foreach (KeyValuePair<string, string> kvp in fooDict)
Console.WriteLine(kvp.Value);
KeyValuePair<string, string> temp = fooDict[1];
fooDict[1] = fooDict[2];
fooDict[2] = temp;
// Print Two, One, Three
foreach (KeyValuePair<string, string> kvp in fooDict)
Console.WriteLine(kvp.Value);
Console.ReadLine();
}
更新:何らかの理由で、自分の回答についてコメントすることはできません。
とにかく、 IndexableDictionary は OrderedDictionary とは異なります。
- 「OrderedDictionary の要素は、どのような方法でも並べ替えられません。」したがって、foreach は数値インデックスに注意を払いません。
- 強く型付けされているため、DictionaryEntry 構造体から何かをキャストする必要はありません。