I want to define a new member method for Dictionary as it already built in member methods eg Add()
, Clear()
, ContainsKey()
etc.
That newly added member method should return all the keyvaluepairs in form of a Set as we can return map.entrySet() to Set in Java.
Can existing methods for dictionary be overridden to achieve this ?
You could create an extension method:
using System;
using System.Collections.Generic;
using System.Linq;
public static class DictionaryExtensions {
public static HashSet<KeyValuePair<TKey, TValue>> ToSet<TKey, TValue>(this Dictionary<TKey, TValue> dict) {
return new HashSet<KeyValuePair<TKey, TValue>>(dict.ToList());
}
}
Info about extension methods: https://msdn.microsoft.com/en-us/library/bb383977(v=vs.110).aspx
I'm aware it's not a set, but by using Linq you can get a list of key value pairs like so:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
List<KeyValuePair<string, string>> keyValuePairs = dictionary.ToList();
Just in case it helps, you can access KeyValue pair of the Dictionary like this :
// Example dictionary
var dic = new Dictionary<int, string>{{1, "a"}};
foreach (var item in dic)
{
Console.WriteLine(string.Format("key : {0}, Value : {1}", item.Key, item.Value));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.