locked
If Dictionary contains Value RRS feed

  • Question

  • I have a Dictionary<int, List<string>>.

    How to check (to return boolean value) if the dictionary contains some value.

     

    I had in mind something like this:

    bool bChecking = dic.Values.Any(... what comes here...); //it has to loop through the each List<T>.

     


    Mitja
    Monday, June 13, 2011 4:08 PM

Answers

  • If you just want to check for a specific value within the list contained in any value, you are on the right track:

     

     

    string searchValue = "Foo";
    bool contained = dic.Values.Any(v => v.Any(s => s == searchValue));
    

     


    The other option would be to flatten the list out, ie:

     

    string searchValue = "Foo";
    bool contained = dic.Values.SelectMany(v => v).Any(s => s == searchValue));
    


    (BTW - I deleted your other off topic message...  In the future, I'd post these types of questions to C# General, as this is an archived forum, and not actively watched now.)

     

     


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Mitja Bonca Monday, June 13, 2011 4:53 PM
    Monday, June 13, 2011 4:33 PM

All replies

  • If you just want to check for a specific value within the list contained in any value, you are on the right track:

     

     

    string searchValue = "Foo";
    bool contained = dic.Values.Any(v => v.Any(s => s == searchValue));
    

     


    The other option would be to flatten the list out, ie:

     

    string searchValue = "Foo";
    bool contained = dic.Values.SelectMany(v => v).Any(s => s == searchValue));
    


    (BTW - I deleted your other off topic message...  In the future, I'd post these types of questions to C# General, as this is an archived forum, and not actively watched now.)

     

     


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Mitja Bonca Monday, June 13, 2011 4:53 PM
    Monday, June 13, 2011 4:33 PM
  • Big thx mate. I knew I was on the right way, I just didnt know how to loop the List<T>.

    For the next time I will post to General. 

    Thx ones again, I really appreciate it.


    Mitja
    Monday, June 13, 2011 4:54 PM