简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM