Reputation: 4907
I've got a list which stores a number of objects. Each object has a property in the form of a variable.
I'd like to be able to check if any of the items in this list contain a certain property. Similar to the Dictionary's ContainsKey method. This data structure is to hold an extremely large amount of values, possibly even millions and I would thus like to use a data structure which can check the properties as fast as possible.
Would Dictionary be the fastest for this job, or are there faster data structures?
EDIT:
Here's a quick, small example of what I'd like to achieve:
Dictionary<string, Person> persons = new Dictionary<string, Person>(); //where string contains the Person's name
bool isPresent = persons.ContainsKey("Matt");
Upvotes: 7
Views: 3201
Reputation: 112632
It depends. If you can load the data into a dictionary once and then query it multiple times, then a dictionary is clearly the fastest possible data structure. If several items can have the same property value, you will have to create a Dictionary<TKey,List<TValue>>
or to use a LINQ Lookup.
However, if you have to load the list each time you query it, then there is no benefit in using a dictionary. You can detect the right properties while loading the list or, if you are querying a database, then try to load just the required data by using an appropriate where clause.
Upvotes: 0
Reputation: 1502835
It sounds like you basically just need a HashSet<T>
containing all the property values - assuming you really just want to know whether it's contained or not.
For example:
var allNames = new HashSet<string>(people.Select(person => person.Name));
Upvotes: 7