Willem said:
The generic Dictionary<T, K> does not have a concept of a begin or an
end,
True.
and cannot be accessed by index.
Mostly true. However, note that you can get the Keys and Values
collections from a Dictionary, and can index those collections (but they
are in enumeration order for the Dictionary, which of course is not
insertion order).
AFAIK, there's no existing
framework class that lets you store key-value pairs *and* have control
over the insertion point, but rolling your own shouldn't be too difficult.
Depending on the specific needs, a SortedDictionary _could_ work. It'd
be a pretty specialized situation though.
A parallel data structure, where there's both a dictionary and a simple
list, would be one approach. Alternatively, if you don't need frequent
access to the data in insertion order, you could create a simple key
type that stores both the key and the order of insertion, which you can
then use as the actual key:
struct OrderedKey<T>
{
public T Key { get; private set; }
public int Order { get; private set; }
public OrderedKey(T key, T order)
{
Key = key;
Order = order;
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
{
return true;
}
OrderedKey<T> t = obj as OrderedKey<T>;
if (t == null)
{
return false;
}
return Key.Equals(t.Key);
}
public override int GetHashCode()
{
return Key.GetHashCode();
}
}
Or something like that. Of course, you'd have to track the insertion
order somehow, such as having a counter in the code where the dictionary
is populated.
With that in hand, you can then enumerate the dictionary in insertion
order as needed:
Dictionary<OrderedKey<string>, DataType> dict = ...;
// dict initialized as needed
foreach (var kvp in dict.OrderBy(x => x.Key.Order))
{
// do something with kvp.Key.Key and/or kvp.Value
}
Finally, I'll note that _in general_, needing to maintain a collection
of objects in both an "order of insertion" and "indexed by key" should
be an unusual situation. I won't say it never comes up, but when
presented with something that looks like you need a solution like that,
I think the first thing to do is double-check your design and make sure
you really need to do that.
Pete