28

I have dictionary which holds my books:

Dictionary<string, book> books

Book definiton:

class book
{
    string author { get; set; }

    string title { get; set; }
} 

I have added some books to the dictionary.

How can I check if there is a book in the Dictionary that matches the title provided by the user?

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
Bublik
  • 912
  • 5
  • 15
  • 30

4 Answers4

41
books.ContainsKey("book name");
Brendan
  • 3,415
  • 24
  • 26
  • 8
    He want to know if it contains a book (value of dictionnary) with a known title property I think, not the dictionnary key. – Amaranth May 03 '12 at 17:59
39

If you're not using the book title as the key, then you will have to enumerate over the values and see if any books contain that title.

foreach(KeyValuePair<string, book> b in books) // or foreach(book b in books.Values)
{
    if(b.Value.title.Equals("some title", StringComparison.CurrentCultureIgnoreCase))
        return true
}

Or you can use LINQ:

books.Any(tr => tr.Value.title.Equals("some title", StringComparison.CurrentCultureIgnoreCase))

If, on the other hand, you are using the books title as the key, then you can simply do:

books.ContainsKey("some title");
SPFiredrake
  • 3,852
  • 18
  • 26
  • THANK YOU, your first code helped, that comes to LINQ, I have never tried it before – Bublik May 03 '12 at 18:11
  • There is .ContainsValue currently in newer version of .net framework. See @ https://msdn.microsoft.com/en-us/library/a63811ah(v=vs.110).aspx – nkalfov Oct 31 '17 at 15:20
6

If you are allowed to use LINQ, try using the below code:

bool exists = books.Any(b => (b.Value != null && b.Value.title == "current title"));
Channs
  • 2,091
  • 1
  • 15
  • 20
2

In your dictionary, does the key hold the title? If yes, use ContainsKey as the other answers. If the key is something else altogether, and you want to check the value's (Book object's) title attribute, you'd have to do it manually like this:

foreach(KeyValuePair<string,book> kvp in books) {
    if (kvp.Value.title == "some title")
        return kvp.Key;
}

return String.Empty; //not found
Ayush
  • 41,754
  • 51
  • 164
  • 239