Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if value already exists

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?

like image 957
Bublik Avatar asked Sep 05 '25 03:09

Bublik


2 Answers

books.ContainsKey("book name");
like image 165
Brendan Avatar answered Sep 10 '25 00:09

Brendan


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");
like image 21
SPFiredrake Avatar answered Sep 10 '25 00:09

SPFiredrake