如何 return IDictionary C# 的所有 KeyValuePairs

How to return all KeyValuePairs of a IDictionary C#

我想写一个 return 包含在 IDictionary 中的所有键值对的方法,就像 Map.EntrySet() 在 java 中所做的那样。

我试过:

例如我们定义IDictionary为:

private IDictionary<T, MutableInt> _map = new Dictionary<T, MutableInt>();    

方法为:

public KeyValuePair<T, MutableInt> KeyValuePairSet()
{
   return KeyValuePair<T, MutableInt>(_map.Keys, _map.Values);
}  

while returning 语句,引发的错误是:

KeyValuePair<T, MutableInt> is a type but used like a variable

这个方法如何实现?

实际上这很容易,因为 IDictionary<TKey, TValue> 实现了接口 IEnumerable<KeyValuePair<TKey, TValue>> 你需要做的就是声明你的 HashSet 并传入字典,因为 HashSet<T> 有一个构造函数接受在一个 IEnumerable<T> 作为它的参数。

public ISet<KeyValuePair<T, MutableInt>> KeyValuePairSet()
{
   return new HashSet<KeyValuePair<T, MutableInt>>(_map);
}  

给定:

private IDictionary<T, MutableInt> map = new Dictionary<T, MutableInt>();

如果你想 return IEnumerable of KeyValuePairs:

IEnumerable<KeyValuePair<T, MutableInt>> get_pairs()
{
   return map;
}

如果要 return KeyValuePair 的键和 map 的值:

KeyValuePair<IEnumerable<T>, IEnumerable<MutableInt>> get_pair()
{
   return new KeyValuePair<IEnumerable<T>, IEnumerable<MutableInt>>(map.Keys, map.Values);
}

如果你想 return HashSet of KeyValuePairs:

ISet<KeyValuePair<T, MutableInt>> get_pairs()
{
   return new HashSet<KeyValuePair<T, MutableInt>>(map);
}