Ras*_*sto 9 .net c# ienumerable idictionary sorteddictionary
当我SortedDictionary<TK, TV>在.NET中,我想枚举它,ICollection<KeyValuePair<TK, TV>>它按预期顺序枚举?
那是KeyValuePair<TK, TV>用最低的键作为第一个返回,后面KeyValuePair<TK, TV>跟第二个最低的键等?
注意:只接受通过引用备份的答案.
是的,当然,尽管您会发现很难找到能够准确阐明这一点的文档。
尽管此类型的四个重载中的每一个的文档GetEnumerator都对返回“迭代集合的枚举器”做出了模糊的陈述,但很明显,它们应该产生等效的(按键排序)序列;请记住,排序字典的含义是“表示按键排序的键/值对的集合”。例如,如果集合在循环和 LINQ to Objects 查询之间的行为完全不同(即具有不同的枚举顺序),那么对于用户来说,这将是非常不直观且令人困惑的。foreach
我能做的就是为您提供您GetEnumerator感兴趣的两种方法的实现(从 .NET 4.0 开始)。它们是相同的 - 它们返回嵌套类型的实例Enumerator,其构造函数具有相同的参数。唯一的区别是第二个重载中结构类型的装箱:
// Used when you do foreach(var kvp in dict) { ... }
public Enumerator<TKey, TValue> GetEnumerator()
{
return new Enumerator<TKey, TValue>
((SortedDictionary<TKey, TValue>) this, 1);
}
// Used when you do:
// foreach(var kvp in (ICollection<KeyValuePair<TKey, TValue>>)dict) { ... }
// or use LINQ to Objects on the collection.
IEnumerator<KeyValuePair<TKey, TValue>>
IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator<TKey, TValue>
((SortedDictionary<TKey, TValue>) this, 1);
}
Run Code Online (Sandbox Code Playgroud)
事实上,实现略有GetEnumerator不同的唯一重载是方法。这会更改构造函数调用的参数,以便生成的枚举器生成实例而不是实例。当然,枚举顺序仍然与其他重载相同。IDictionary.GetEnumeratorDictionaryEntryKeyValuePair<,>
| 归档时间: |
|
| 查看次数: |
1754 次 |
| 最近记录: |