我有一本字典fooDictionary<string, MyObject>
。
我正在过滤fooDictionary
,只获取具有该属性特定值的MyObject
。
//(Extension method is a extension method that I made for the lists
//(PS: ExtensionMethod returns only 1x MyObject))
fooDictionary.Values.Where(x=>x.Boo==false).ToList().ExtensionMethod();
但我也希望获得已经过滤的MyObject's
的密钥。我怎样才能做到这一点?
答案 0 :(得分:5)
不要只提取值,而是查询KeyValuePair
fooDictionary.Where(x => !x.Value.Boo).ToList();
这将为您提供MyObject
的{{1}}值为false的所有键值对。
注意:我将您的行Boo
更改为x.Value.Boo == false
,因为这是更常见的语法,并且(恕我直言)更容易阅读/理解意图。
修改强>
根据您更新问题以更改从处理列表到此新!x.Value.Boo
这里是一个更新的答案(我将其余部分保留,因为它回答了原始发布的问题)。
ExtensionMethod
并像这样使用
// Note this is assuming you can use the new ValueTuples, if not
// then you can change the return to Tuple<string, MyObject>
public static (string key, MyObject myObject) ExtensionMethod(this IEnumerable<KeyValuePair<string, MyObject>> items)
{
// Do whatever it was you were doing here in the original code
// except now you are operating on KeyValuePair objects which give
// you both the object and the key
foreach(var pair in items)
{
if ( YourCondition ) return (pair.Key, pair.Value);
}
}