I have an array of elements that I need to access quite often, and quite fast. I know that a property from those elements is unique and I inject the array into a wrapper class, which builds a dictionary from this property. Since a dictionary access is way faster than a LINQ query on the array, I thought that'd be efficient.
But, despite it is working well, the solution looks a bit weird : I am storing the object as a value into the dictionary, and part of it as a key.
Is there any better suited structure/way of doing it?
public class FooItem
{
public string Id { get; set; } //UNIQUE
public double Value1 { get; set; }
public string Value2 { get; set; }
}
public class FoosManager
{
private Dictionary<string, FooItem> _dic;
public FooManager(IEnumerable<FooItem> items) {
_dic = new Dictionary<string, FooItem>(
items.ToDictionary(x => x.Id, x => x),
StringComparer.OrdinalIgnoreCase);
}
public FooItem this[string id] => GetItem(id); //Indexer
private FooItem GetItem(string id) {
if (_dic.ContainsKey(id))
return null;
return _dic[id];
}
}