Reputation: 357
I have a large dictionary of pre-computed values of type in a C# dictionary.
Now I have a search string, I need to find all entries in the dictionary where the search string is part of "string" value.i.e Say I have,
Dictionary<PersonId, PersonDescription> values;
Search string is "office" I would need to find all entries in the dictionary where PersonDescription string value contains the term "office".
How best to search in the fastest way possible?
Upvotes: 0
Views: 626
Reputation: 38825
Dictionaries are optimised on accessing by the key. So, you're going to have to iterate over every single element anyway to see if the value contains the key. Here's two potential ways:
Iterate
List<PersonDescription> found = new List<PersonDescription>();
foreach(var pair in values)
{
if(pair.Value.SomeField.Contains("office"))
found.Add(pair.Value);
}
Note that the above adds the PersonDescription
, you might want to add PersonId
.
Use a KeyedCollection class (and then iterate)
You'll have to derived a class from this (but it's simple) (also assumes PersonId
is a member of PersonDescription
:
using System.Collections.Generic.ObjectModel
public class PersonDictionary : KeyedCollection<int, PersonDescription>
{
protected override int GetKeyforItem(PersonDescription description)
{
return description.Personid; // hope it's on this class!
}
}
Now you can iterate over this, and also access it randomly:
List<PersonDescription> found = new List<PersonDescription>();
for(int i = 0; i < values.Count; ++i)
{
if(values[i].Field.Contains("office"))
found.Add(values[i]);
}
You can substitute the manual loops specified above for LINQ if you prefer.
Dictionaries are generally used because you want a fast look up by a key. I am not saying this is an XY Problem, but it smells like it. Alternatively you might actually need to access a dictionary both by key and by searching all items
Upvotes: 2
Reputation: 25370
string searchTerm = "office";
var PeopleIDs = dict.Where(person => person.Value.Contains(searchTerm))
.Select(item => item.Key);
Do you want something more complex than that?
Upvotes: 1