1

I want to define a new member method for Dictionary as it already built in member methods e.g. 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 ?

maliks
  • 1,102
  • 3
  • 18
  • 42

3 Answers3

2

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

Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56
0

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();
Richard
  • 560
  • 1
  • 8
  • 17
0

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));
}
Edgars Pivovarenoks
  • 1,526
  • 1
  • 17
  • 31
  • I want to have a method which return all KeyValuePair of the Dictionary which I can call as an extension method – maliks Jun 04 '16 at 15:44