使用VB.net
我有两个List(Of String)
以下是我如何找到两个列表之间的共同项目:
Sub Main()
Dim lstOne As New List(Of String)() _
From {"Jim", "Jack", "Kate", "Nope"}
Dim lstTwo As New List(Of String)() _
From {"Jack", "Nope", "Jim"}
Dim lstNew As IEnumerable(Of String) = Nothing
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
End Sub
我想使用Linq在这两个列表中找到不常见的项目。
我该怎么做?
答案 0 :(得分:3)
像这样:
Sub Main()
Dim lstOne As New List(Of String)() _
From {"Jim", "Jack", "Kate", "Nope"}
Dim lstTwo As New List(Of String)() _
From {"Jack", "Nope", "Jim"}
Dim lstNew As IEnumerable(Of String) = Nothing
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
Dim uncommon As IEnumerable(Of String) = lstOne.Union(lstTwo).Except(lstNew, StringComparer.OrdinalIgnoreCase)
For Each element As String In uncommon
Console.WriteLine(element)
Next
End Sub
输出:
Kate
答案 1 :(得分:1)
要坚持纯LINQ,您可以使用Except
:
Dim inOneNotTwo As IEnumerable(Of String) = lstOne.Except(lstNew)
Dim inTwoNotOne As IEnumerable(Of String) = lstTwo.Except(lstNew)
或者,您可以使用HashSet(Of T)
和SymmetricExceptWith
:
Dim strings As HashSet(Of String) = new HashSet(Of String)(lstOne)
strings.SymmetricExceptWith(lstTwo)