问题描述
我有一个列表
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来S
what is the best way to do a check before i add a new "MyObject" to thsi list of "MyObject"s
我想出的唯一的解决办法是从列表更改为字典和他们做出关键的属性的连接字符串(这似乎有点unelegant)
the only solution i thought up was to change from a list to a dictionary and them make the key a concatenated string of the properties (this seems a little unelegant)
使用列表或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:
- 这份名单是相对稳定的(没有进行大量插入/缺失,这些词典都没有优化的)
- 列表是相当大的(否则字典的开销是没有意义的)。
如果以上都不是真正适合您的情况,只需使用 :
If the above are not true for your situation, just use 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.
这篇关于如何检查的对象列表中已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!