gpt4 book ai didi

vb.net - 如何在多个 List(of) 中找到共同元素?

转载 作者:行者123 更新时间:2023-12-01 12:43:08 26 4
gpt4 key购买 nike

我有如下三个列表

Dim foodList1 As New List(Of Food)
Dim foodList2 As New List(Of Food)
Dim foodList3 As New List(Of Food)

Dim resualt = From c In db.Food
Where c.Code = X
Select c

m_FoodList1 = resualt.ToList

我需要创建一个新列表,其中包含这三个列表共有的食物。有没有我可以使用的方法而不是通过列表并比较它们?提前谢谢你

最佳答案

您可以使用 Intersect()为此目的的方法。这适用于内部的 HashSet,因此它的性能非常好:

Dim result = foodList1.Intersect(foodList2).Intersect(foodList3)

如果 Food 类还没有覆盖 EqualsGetHashCode,您可以创建一个特殊的 IEqualityComparer并将其作为参数提供给 Intersect :

Class FoodEqualityComparer
Implements IEqualityComparer(Of Food)

Public Function Equals(x As Food, y As Food) As Boolean Implements IEqualityComparer(Of Food).Equals
Return x.Code = y.Code
End Function

Public Function GetHashCode(x As Food) As Integer Implements IEqualityComparer(Of Food).GetHashCode
Return x.Code.GetHashCode()
End Function
End Class

' ...

Dim eqComp As New FoodEqualityComparer()
Dim result = foodList1.Intersect(foodList2, eqComp).Intersect(foodList3, eqComp)

关于vb.net - 如何在多个 List(of) 中找到共同元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22452168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com