比较两个列表以获取同时出现在两个列表中的对象

大卫·B

我有两个相同类的列表,并且想要生成两个列表中都出现的对象数。

Dim repeatingMentions As Integer 
repeatingMentions =currentMentions.Where(Function(m) previousMentions.Contains(m)).Count

调试我可以看到两个列表包含的对象具有完全相同的属性值,这足以满足包含的要求,因为计数返回为0。

蒂姆·施密特(Tim Schmelter)

您必须重写Equals+GetHashCode或提供一个自定义项IEqualityComparer(Of YourClassName)才能使用Contains或者您必须使用Any

repeatingMentions  = currentMentions.
    Count(Function(m) previousMentions.
        Any(Function(p) m.PropertyName = p.PropertyName))

或者,您也可以通过加入两个列表Enumerable.Join

Dim inBoth = From currMent In currentMentions
             Join prevMent In previousMentions
             On currMent.PropertyName Equals prevMent.PropertyName
repeatingMentions = inBoth.Count()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章