Home > OS >  Filter a Dictionary by value where value is a list of string using LINQ
Filter a Dictionary by value where value is a list of string using LINQ

Time:04-06

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?

CodePudding user response:

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>>

  • Related