首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在OrderedDictionary中反向迭代

如何在OrderedDictionary中反向迭代
EN

Stack Overflow用户
提问于 2017-01-18 10:49:49
回答 6查看 2.8K关注 0票数 2

如何反向遍历OrderedDictionary并访问其密钥?

由于它不支持LINQ扩展,所以我尝试了以下方法:

代码语言:javascript
复制
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];
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2017-01-18 11:23:37

您可以通过使用常规的Dictionary (或SortedDictionary,取决于您的需求)并保持一个二级List来跟踪键的插入顺序,从而大大降低这个问题的复杂性。您甚至可以使用一个类来帮助这个组织:

代码语言:javascript
复制
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]];
    }
}

(当然,还可以添加所需的任何其他方法。)

票数 2
EN

Stack Overflow用户

发布于 2017-01-18 10:53:11

我可以建议使用SortedDictionary<K, V>吗?它确实支持LINQ,并且它是类型安全的:

代码语言:javascript
复制
var orderedDictionary = new SortedDictionary<string, string>();
orderedDictionary.Add("something", "a");
orderedDictionary.Add("another", "b");

foreach (KeyValuePair<string, string> kvp in orderedDictionary.Reverse())
{
}

另外,正如Ivan在评论中指出的那样,OrderedDictionary的返回项根本没有排序,所以SortedDictionary就是您想要的。

票数 3
EN

Stack Overflow用户

发布于 2017-01-18 11:51:16

因为它不支持LINQ扩展..。

那是因为它是一个非通用的Enumerable。通过将其转换为正确的类型,可以使其成为通用的:

代码语言:javascript
复制
foreach (var entry in orderedDictionary.Cast<DictionaryEntry>().Reverse()) {
    var key = entry.Key;
    var value = entry.Value;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41717399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档