如何检查对象是否已存在于列表中 [英] how to check if object already exists in a list
问题描述
我有一个清单
List<MyObject> myList
我正在向列表中添加项目,我想检查该对象是否已经在列表中.
and I am adding items to a list and I want to check if that object is already in the list.
所以在我这样做之前:
myList.Add(nextObject);
我想看看 nextObject 是否已经在列表中.
I want to see if nextObject is already in the list.
对象MyObject"有许多属性,但比较是基于两个属性的匹配.
The object "MyObject" has a number of properties but comparison is based on matching on two properties.
在将新的MyObject"添加到此MyObject"列表之前进行检查的最佳方法是什么.
What is the best way to do a check before I add a new "MyObject" to this list of "MyObject"s.
我想到的唯一解决方案是从列表更改为字典,然后将键设为属性的连接字符串(这似乎有点不雅).
The only solution I thought up was to change from a list to a dictionary and then make the key a concatenated string of the properties (this seems a little unelegant).
任何其他使用 list 或 LINQ 或其他东西的更清洁的解决方案?
Any other cleaner solutions using list or LINQ or something else?
推荐答案
这要看具体情况的需要了.例如,假设以下情况,字典方法会非常好:
It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:
- 列表相对稳定(插入/删除不是很多,字典没有针对这些进行优化)
- 列表非常大(否则字典的开销毫无意义).
如果上述情况不适用于您的情况,请使用方法 Any()
:
If the above are not true for your situation, just use the method Any()
:
Item wonderIfItsPresent = ...
bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);
这将遍历列表,直到找到匹配项,或者直到到达末尾.
This will enumerate through the list until it finds a match, or until it reaches the end.
这篇关于如何检查对象是否已存在于列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!