Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 674
Juri Bogdanov Avatar asked Mar 16 '26 14:03

Juri Bogdanov


1 Answers

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();
like image 171
maciejkow Avatar answered Mar 18 '26 04:03

maciejkow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!