【问题标题】:C# Dictionary filtering (LINQ) values and getting the keyC# 字典过滤 (LINQ) 值并获取密钥
【发布时间】:2018-05-27 19:08:46
【问题描述】:

我有一本字典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 的密钥。我怎样才能做到这一点?

【问题讨论】:

  • 不确定你真正想要什么,你能添加一些必需的输出吗?
  • fooDictioanry.Where(x => !x.Value.Boo)
  • FooDictionary.Where(x => !x.Value.Boo).Select(x => x.Key)
  • “已经过滤”是什么意思?
  • @elgonzo ExtensionMethod 仅返回 1 个 MyObject

标签: c# linq dictionary


【解决方案1】:

不只是提取值,而是查询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();

【讨论】:

  • 你打败了我。删除了我的。
  • @pstrjds 抱歉,我忘了提及有关过滤的重要内容,请重新检查我的问题
  • @john - 所以你的扩展方法需要一个List&lt;MyObject&gt;,然后根据其他一些内部标准给你一个MyObject?我的理解正确吗?您至少可以为其发布一些伪代码或显示方法签名。通过添加它,您基本上已经完全改变了您的问题,所以我需要更改或删除我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 2019-05-25
相关资源
最近更新 更多