joh*_*ohn -1 c# linq dictionary
我有一本字典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();
Run Code Online (Sandbox Code Playgroud)
但我也希望获得已经过滤的密钥MyObject's.我怎样才能做到这一点?
不仅仅是拉取值,而是查询KeyValuePair
fooDictionary.Where(x => !x.Value.Boo).ToList();
Run Code Online (Sandbox Code Playgroud)
这将为您MyObject提供Boo值为false的所有键值对.
注意:我将您的行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);
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
(string key, MyObject myObject) = fooDictionary.Where(x => !x.Value.Boo).ExtensionMethod();
Run Code Online (Sandbox Code Playgroud)