如何反向遍历OrderedDictionary并访问其密钥?
由于它不支持LINQ扩展,所以我尝试了以下方法:
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];
}发布于 2017-01-18 11:23:37
您可以通过使用常规的Dictionary (或SortedDictionary,取决于您的需求)并保持一个二级List来跟踪键的插入顺序,从而大大降低这个问题的复杂性。您甚至可以使用一个类来帮助这个组织:
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]];
}
}(当然,还可以添加所需的任何其他方法。)
发布于 2017-01-18 10:53:11
我可以建议使用SortedDictionary<K, V>吗?它确实支持LINQ,并且它是类型安全的:
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就是您想要的。
发布于 2017-01-18 11:51:16
因为它不支持LINQ扩展..。
那是因为它是一个非通用的Enumerable。通过将其转换为正确的类型,可以使其成为通用的:
foreach (var entry in orderedDictionary.Cast<DictionaryEntry>().Reverse()) {
var key = entry.Key;
var value = entry.Value;
}https://stackoverflow.com/questions/41717399
复制相似问题