Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built-in List that can be accessed by index and key

Is it possible to create a list that can be access by either an index or a key?

I am looking for a Collection type that already exists but has this facility, I want to avoid redefining the indexers

like image 409
Graviton Avatar asked Dec 30 '22 08:12

Graviton


1 Answers

There's a similar question at What is the best data structure in .NET for look-up by string key or numeric index?.

Have a look at KeyedCollection:

class IndexableDictionary<TKey, TItem> : KeyedCollection<TKey, TItem>
 { Dictionary<TItem, TKey> keys = new Dictionary<TItem, TKey>();

   protected override TKey GetKeyForItem(TItem item) { return keys[item];}

   public void Add(TKey key, TItem item) 
    { keys[item] = key;
      this.Add(item);
    }
 }
like image 140
Mark Cidade Avatar answered Jan 08 '23 16:01

Mark Cidade