'Filter a Dictionary by value where value is a list of string using LINQ

I have a dictionary with the following structure: Dictionary<string, List<string>>

For example, I wanted to retrieve all the entry that have as a value a string longer than 3 character, this is what I've tried:

mydictionary.Where(s => s.Value.Where(word => word.Length == 3).ToList().Count > 0) as Dictionary<string, List<string>>

But what I get is a null value, what I'm doing wrong?



Solution 1:[1]

You can exploit Any method instead of Where and Count:

var result = mydictionary
  .Where(pair => pair.Value.Any(word => word.Length > 3)) // longer than 3 chars
  .ToDictionary(pair => pair.Key, pair => pair.Value);

Note, that you should materialize with a help of ToDictionary instead of cast as Dictionary<string, List<string>>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Bychenko