[英]Defining new Dictionary members methods C#
I want to define a new member method for Dictionary as it already built in member methods eg Add()
, Clear()
, ContainsKey()
etc. 我想为Dictionary定义一个新的成员方法,因为它已经内置在成员方法中,例如Add()
, Clear()
, ContainsKey()
等。
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. 新添加的成员方法应该以Set的形式返回所有键值对,因为我们可以在Java中将map.entrySet()返回给Set。
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 有关扩展方法的信息: https : //msdn.microsoft.com/zh-cn/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: 我知道这不是一个集合,但是通过使用Linq,您可以像这样获得键值对的列表:
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 : 以防万一,您可以像这样访问Dictionary的KeyValue对:
// 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.