There is no such thing as a key index. You should always treat Dictionary<TKey, TValue> as an unpredictable order โ where the order you get when you repeat it may change. (So, theoretically, you can add one new record, and the records may be in a completely different order the next time you repeat them. Theoretically, this can happen without changing the data, but this is less likely in normal implementations.)
If you really want to get the numerical index that you observed this time, you can use:
foreach (var x in dictionary.Select((Entry, Index) => new { Entry, Index })) { Console.WriteLine("{0}: {1} = {2}", x.Index, x.Entry.Key, x.Entry.Value); }
... but keep in mind that this is a pretty misleading display as it offers a built-in order.
From the documentation :
For enumeration purposes, each element in the dictionary is considered as a structure KeyValuePair<TKey, TValue> , representing the value and its key. The order in which elements are returned is undefined.
EDIT: if you don't like the Select call here, you can create your own extension method:
public struct IndexedValue<T> { private readonly T value; private readonly int index; public T Value { get { return value; } } public int Index { get { return index; } } public IndexedValue(T value, int index) { this.value = value; this.index = index; } } public static class Extensions { public static IEnumerable<IndexedValue<T>> WithIndex<T> (this IEnumerable<T> source) { return source.Select((value, index) => new IndexedValue<T>(value, index)); } }
Then your loop will look like this:
foreach (var x in dictionary.WithIndex()) { Console.WriteLine("{0}: {1} = {2}", x.Index, x.Value.Key, x.Value.Value); }
Jon skeet
source share