Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate in reverse through an OrderedDictionary

How can I iterate through an OrderedDictionary in reverse and access its keys?

Since it doesn't have any support for LINQ extensions, I have tried the following:

var orderedDictionary= new OrderedDictionary();
orderedDictionary.Add("something", someObject);
orderedDictionary.Add("another", anotherObject);

for (var dictIndex = orderedDictionary.Count - 1; dictIndex != 0; dictIndex--)
{
    // It gives me the value, but how do I get the key?
    // E.g., "something" and "another".
    var key = orderedDictionary[dictIndex];
}
like image 419
pelican_george Avatar asked Feb 22 '26 23:02

pelican_george


1 Answers

You can lessen the complexity of this problem significantly by using a regular Dictionary (or SortedDictionary, depending on your requirements) and keep a secondary List to keep track of the keys' insertion order. You can even use a class to facilitate this organization:

public class DictionaryList<TKey, TValue>
{
    private Dictionary<TKey, TValue> _dict;
    private List<TKey> _list;

    public TValue this[TKey key]
    {
        get { return _dict[key]; }
        set { _dict[key] = value; }
    }

    public DictionaryList()
    {
        _dict = new Dictionary<TKey, TValue>();
        _list = new List<TKey>();
    }

    public void Add(TKey key, TValue value)
    {
        _dict.Add(key, value);
        _list.Add(key);
    }

    public IEnumerable<TValue> GetValuesReverse()
    {
        for (int i = _list.Count - 1; i >= 0; i--)
            yield return _dict[_list[i]];
    }
}

(And of course add whatever other methods you need as well.)

like image 92
Abion47 Avatar answered Feb 24 '26 11:02

Abion47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!