且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查的对象列表中已经存在

更新时间:2023-11-25 23:09:16

这要看具体情况的需要。例如,字典的方法是相当不错的假设:

It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:


  1. 这份名单是相对稳定的(没有进行大量插入/缺失,这些词典都没有优化的)

  2. 列表是相当大的(否则字典的开销是没有意义的)。

如果以上都不是真正适合您的情况,只需使用 任何()

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.