Search code examples
c#linq.net-3.5linq-to-entities

Testing if a value is contained within a Dictionary<TKey, List<TValue>>


I need to determine if any of the Lists contained in the Dictionary contain the specified value. I'm new to LINQ, so is the following the correct way to achieve this?

Dictionary lotsOfStuff = new Dictionary<string, List<string>>();
string searchString;

// populate lotsOfStuff and searchString...

// detemine if any of the values of lotsOfStuff contain searchString
bool existsInDictionary = lotsOfStuff.Values.Any(values => values.Contains(searchString));

And if the above will work, is there any way to make it more correct or more optimal/concise?


Solution

  • This code works and is about as efficient as it can be. Because you are searching values there is no index/hash to guide the search. Hence you must search all objects to determine if the value does or does not exist.