Reputation: 1112
I want to write a method which return all key value pairs containing in a IDictionary
as Map.EntrySet() does in java.
I tried as:
For example we define IDictionary
as:
private IDictionary<T, MutableInt> _map = new Dictionary<T, MutableInt>();
The method as:
public KeyValuePair<T, MutableInt> KeyValuePairSet()
{
return KeyValuePair<T, MutableInt>(_map.Keys, _map.Values);
}
while returning statement, the error raised is:
KeyValuePair<T, MutableInt> is a type but used like a variable
How can this method be implemented?
Upvotes: 4
Views: 1424
Reputation: 3319
Given:
private IDictionary<T, MutableInt> map = new Dictionary<T, MutableInt>();
If you want to return IEnumerable
of KeyValuePair
s:
IEnumerable<KeyValuePair<T, MutableInt>> get_pairs()
{
return map;
}
If you want to return KeyValuePair
of keys and values of map
:
KeyValuePair<IEnumerable<T>, IEnumerable<MutableInt>> get_pair()
{
return new KeyValuePair<IEnumerable<T>, IEnumerable<MutableInt>>(map.Keys, map.Values);
}
If you want to return HashSet
of KeyValuePair
s:
ISet<KeyValuePair<T, MutableInt>> get_pairs()
{
return new HashSet<KeyValuePair<T, MutableInt>>(map);
}
Upvotes: 3
Reputation: 127563
Actually it is fairly easily, because IDictionary<TKey, TValue>
implmentents the interface IEnumerable<KeyValuePair<TKey, TValue>>
all you need to do is declare your HashSet and pass the dictionary in because HashSet<T>
has a constructor that takes in a IEnumerable<T>
as its parameter.
public ISet<KeyValuePair<T, MutableInt>> KeyValuePairSet()
{
return new HashSet<KeyValuePair<T, MutableInt>>(_map);
}
Upvotes: 3