简体   繁体   中英

How to use Dictionary.Values.Where <TSource> (Func<TSource,bool> predicate) to find needed values?

I have dictionary, like

Dictionary<string, bool> accValues = new Dictionary<string, bool>()

And I want to get bool value for specific key. I can do it via foreach, like

foreach (KeyValuePair<string, bool> keypair in accValues)
            {
                if (keypair.Key == "SomeString")
                {
                    return keypair.Value;
                }
            }

But how is it possible to realize using Where function?

Why iterate over every key/value pair? Use

accValues["SomeString"]

or, if you don't want an exception to be thrown when no such key exists in the dictionary:

accValue.TryGetValue("SomeString", out boolValue)

if you want to find a value for a key that matches some arbitrary predicate, you can use a statement like this:

accValues.Where(kvp => kvp.Key == "SomeString").Select(kvp => kvp.Value).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM