确认是否已经存在

问题描述 投票:21回答:5

我有一本字典,里面装着我的书。

Dictionary<string, book> books

书的定义。

class book
{
    string author { get; set; }

    string title { get; set; }
} 

我在字典中添加了一些书籍。

如何检查字典中是否有与用户提供的书名相符的书?

c# dictionary contains
5个回答
33
投票

如果你不使用书名作为键,那么你将不得不枚举这些值,看看是否有任何书籍包含该标题。

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
}

或者你可以使用LINQ。

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

如果,另一方面,你使用书名作为键, 那么你可以简单地做:

books.ContainsKey("some title");

36
投票
books.ContainsKey("book name");

6
投票

如果你被允许使用LINQ,请尝试使用下面的代码。

bool exists = books.Any(b => (b.Value != null && b.Value.title == "current title"));

2
投票

在你的字典中,键是否包含书名?如果是,使用 ContainsKey 作为其他答案。如果键是其他的东西,而你想检查值(Book对象的)的 title 属性,你必须像这样手动操作。

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

return String.Empty; //not found
© www.soinside.com 2019 - 2024. All rights reserved.