Use SortedList<TKey,TValue> , Dictionary<TKey, TValue> or System.Collections.ObjectModel.KeyedCollection<TKey, TValue> for key-based quick access.
var list = new List<myObject>(); // Search is sequential var dictionary = new Dictionary<myObject, myObject>(); // key based lookup, but no sequential lookup, Contains fast var sortedList = new SortedList<myObject, myObject>(); // key based and sequential lookup, Contains fast
KeyedCollection<TKey, TValue> also fast and allows you to index your search, however you need to inherit it because it is abstract. Therefore, you need a certain collection. However, with the following, you can create a generic KeyedCollection .
public class GenericKeyedCollection<TKey, TValue> : KeyedCollection<TKey, TValue> { public GenericKeyedCollection(Func<TValue, TKey> keyExtractor) { this.keyExtractor = keyExtractor; } private Func<TValue, TKey> keyExtractor; protected override TKey GetKeyForItem(TValue value) { return this.keyExtractor(value); } }
The advantage of using KeyedCollection is that the Add method does not require a key.
Axelckenberger
source share