C# 字典筛选 (LINQ) 值并获取密钥



我有一个字典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的密钥.我该怎么做?

不要只是拉取值,而是查询 KeyValuePair

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

这将为您提供MyObjectBoo值为 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);
}
}

并像这样使用它

(string key, MyObject myObject) = fooDictionary.Where(x => !x.Value.Boo).ExtensionMethod();

最新更新