c# - .Net Dictionary of Type using a member as key -
i've been working dictionaries typed custom class, , key them off external value. better encapsulation, i'd use 1 of properties of class key value. there simple way without creating custom implementation of dictionary?
example:
public class mystuff{ public int num{get;set;} public string val1{get;set;} public string val2{get;set;} } var dic = new dictionary<int, mystuff>();
is there option resembling instead? -
var dic = new dictionary<x=> x.num, mystuff>();
i think you're looking keyedcollection<tkey, titem>
unlike dictionaries, element of
keyedcollection<tkey, titem>
not key/value pair; instead, entire element value , key embedded within value. example, element of collection derivedkeyedcollection<string,string>
(keyedcollection(of string, string)
in visual basic) might "john doe jr." value "john doe jr." , key "doe"; or collection of employee records containing integer keys derivedkeyedcollection<int,employee>
. abstractgetkeyforitem
method extracts key element.
you create derived class implements getkeyforitem
via delegate:
public class projectedkeycollection<tkey, titem> : keyedcollection<tkey, titem> { private readonly func<titem, tkey> keyselector; public projectedkeycollection(func<titem, tkey> keyselector) { this.keyselector = keyselector; } protected override tkey getkeyforitem(titem item) { return keyselector(item); } }
then:
var dictionary = new projectedkeycollection<int, mystuff>(x => x.num);
Comments
Post a Comment