C#字典过滤(LINQ)值并获取密钥 [英] C# Dictionary filtering (LINQ) values and getting the key

查看:125
本文介绍了C#字典过滤(LINQ)值并获取密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字典fooDictionary<string, MyObject>.

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

I am filtering the fooDictionary to get only the MyObject with a specific value of the property.

//(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的键.我怎样才能做到这一点?

But I also want to get the keys of the already filtered MyObject's. How can I do that?

推荐答案

查询这将为您提供MyObjectBoo值为false的所有键值对.

This will give you all the key value pairs where the MyObject has a Boo value of false.

注意:我将您的行x.Value.Boo == false更改为!x.Value.Boo,因为这是更常见的语法,并且(IMHO)更易于阅读/理解意图.

Note: I changed your line x.Value.Boo == false to !x.Value.Boo as that is the more common syntax and is (IMHO) easier to read/understand the intent.

编辑

根据您将问题更新为从处理列表更改为新的问题ExtensionMethod,这是更新的答案(我将其余部分保留原样,因为它回答的是原始发布的问题).

Based on you updating the question to change from dealing with a list to this new ExtensionMethod here is an updated answer (I am leaving the rest as is as it answers what the original posted question was).

// 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();

这篇关于C#字典过滤(LINQ)值并获取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆