I need to implement a search algoritm with efficient o(1). If I use HashSet and will try search by User.FirstName for example, whether it is right? If not, give me an开发者_JS百科 advice, please, how can I realize this search?
You'll need to use Dictionary<TKey,TValue>
, where the TKey
is built on the search type. However, if you're using something like FirstName
as a search term, you may have multiple values with the same key, which will cause problems.
A potentially better option would be to use ToLookup to generate an ILookup
for you. For example:
IEnumerable<Person> people = GetPeople();
var nameLookup = people.ToLookup(p => p.FirstName);
You could then do:
var peopleNamedFred = nameLookup["Fred"];
foreach(var fred in peopleNamedFred)
Console.WriteLine("{0} {1}, fred.FirstName, fred.LastName);
Create an implementation of System.Collections.ObjectModel.KeyedCollection
.
According to the MSDN reference it " provides both O(1) indexed retrieval and keyed retrieval that approaches O(1)." However, it still has the limitations that Dictionary' and
HashTable` have with duplicate keys not being allowed. If you need duplicate key values, or you need to be able to use different items as keys at different times, then Reed Copsey gives a very good solution.
精彩评论