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 derived keyedcollection<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 derived keyedcollection<int,employee>. abstract getkeyforitem 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

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -