C# 检查值是否已经存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10436813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if value already exists
提问by Bublik
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?
如何检查字典中是否有与用户提供的书名相匹配的书?
采纳答案by SPFiredrake
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:
或者您可以使用 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");
回答by Brendan
books.ContainsKey("book name");
回答by xbonez
In your dictionary, does the key hold the title? If yes, use ContainsKeyas the other answers. If the key is something else altogether, and you want to check the value's (Book object's) titleattribute, you'd have to do it manually like this:
在您的字典中,键是否包含标题?如果是,请ContainsKey用作其他答案。如果键完全不同,并且您想检查值的(Book 对象的)title属性,则必须像这样手动执行此操作:
foreach(KeyValuePair<string,book> kvp in books) {
if (kvp.Value.title == "some title")
return kvp.Key;
}
return String.Empty; //not found
回答by Channs
If you are allowed to use LINQ, try using the below code:
如果您可以使用 LINQ,请尝试使用以下代码:
bool exists = books.Any(b => (b.Value != null && b.Value.title == "current title"));

