Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

C# Dictionary filtering (LINQ) values and getting the key

I have a dictionary fooDictionary<string, 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(); 

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of just pulling the values, query the KeyValuePair

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

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

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.

EDIT

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);
    }
}

And use it like this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...