我的字典持有我的书:检查是否值已经存在
Dictionary<string, book> books
书definiton:
class book
{
string author { get; set; }
string title { get; set; }
}
我已经添加了一些书字典。
如何检查字典中是否有与用户提供的标题匹配的图书?
我的字典持有我的书:检查是否值已经存在
Dictionary<string, book> books
书definiton:
class book
{
string author { get; set; }
string title { get; set; }
}
我已经添加了一些书字典。
如何检查字典中是否有与用户提供的标题匹配的图书?
如果您不使用书名作为键,那么您将不得不枚举所有值并查看是否有任何书籍包含该标题。
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");
在你的字典中,密钥是否包含标题?如果是,则使用ContainsKey
作为其他答案。如果关键是别的东西完全,并且要检查值的(Book对象的)title
属性,你不得不手动做这样的:
foreach(KeyValuePair<string,book> kvp in books) {
if (kvp.Value.title == "some title")
return kvp.Key;
}
return String.Empty; //not found
如果你被允许使用LINQ,尝试使用下面的代码:
bool exists = books.Any(b => (b.Value != null && b.Value.title == "current title"));
你提供'''字符串'部分的值是什么? –
zimdanen