使用成员作为关键的字典 [英] Dictionary using member as key
问题描述
你有多少次创建了一个如下所示的字典:
how many times have you created a dictionary that looks like this:
MyClass a;
var data = new Dictionary<string, MyClass>();
data.Add(a.Name,a);
或者更糟糕的是:
Or maybe worse:
var data = new Dictionary<string, string>();
data.Add(a,a);
如果我们可以创建一个将键绑定到成员的字典怎么办? ?
类似于:
what if we could create a Dictionary that bound the key to a member?
something like:
MyClass a;
var data = new MemberBindingDictionary<MyClass>("Name");
data.Add(a);
if(data.ContainsKey(a.Name))
{
...
}
我找不到类似的东西。那是因为这是一个愚蠢的想法吗?还是太贵了?
I couldn''t find anything like it. Is that because it''s a stupid idea? or is it too expensive?
推荐答案
这里没有班级在C#中。但你可以自己创建一个类:
Hi,
There''s not a class like that in C#. But you can create a class like that yourself:
public class MemberBindingDictionary<T>:Dictionary<object, T>
{
Func<T,object> _binding = null;
public MemberBindingDictionary(Func<T,object> binding)
{
_binding = binding;
}
public void Add(T value)
{
this.Add(_binding(value), value);
}
}
我没有使用字符串
作为参数构造函数,但 Func
。现在,您可以使用此类,并使用lambda表达式将值绑定到键:
I don''t use a string
as a parameter in the constructor, but a Func
. Now, you can use this class, and bind the value to a key using a lambda expression:
MyClass a;
var data = new MemberBindingDictionary<MyClass>(x => x.Name);
data.Add(a);
if(data.ContainsKey(a.Name))
{
...
}
所以,不要写姓名
,但要写 x => x.Name
。这是一个 lambda表达式 [ ^ ]
希望这有帮助。
格式化问题已修复[/编辑]
So, don''t write "Name"
, but write x => x.Name
. This is a lambda expression[^]
Hope this helps.
Formatting problems fixed[/Edit]
我可能会像这样使用MyClass数组的链接。
I would probably just use link with an array of MyClass like this.
IEnumerable<myclass> data = new MyClass[] { new MyClass("Greg"), new MyClass("Peter"), new MyClass("Bobby") };
if (data.Count(x => x.Name == "Peter") > 0)
{
// Do something.
}
这篇关于使用成员作为关键的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!