首页 > 解决方案 > C# 字典过滤 (LINQ) 和列表扩展方法过滤值并获取密钥

问题描述

我有一本字典fooDictionary<string, MyObject>

我正在过滤fooDictionary以仅获取具有特定属性值的 MyObject 。

fooDictionary.Values.Where(x=>x.Boo==false).ToList().ExtensionMethod();

//(扩展方法是我为列表制作的扩展方法(用于更多过滤)(PS:ExtensionMethod仅返回1x MyObject))但我也想获取已经过滤的MyObject的键。我怎样才能做到这一点?

标签: c#linqdictionary

解决方案


When you operate on the dictionary values with fooDictionary.Values.Where(...), you no longer have access to the keys.

instead change the query to:

fooDictionary.Where(x => x.Value.Boo == false).ToList().ExtensionMethod();

After the ToList() call, this should yield a List<KeyValuePair<string, MyObject>> hence maintaining both the key as well as the corresponding value.


推荐阅读