获取2个列表之间不匹配的所有成员

时间:2016-03-29 14:14:53

标签: vb.net linq

我正在使用vb.net :(

我有2个列表集合,我想返回第3个集合,其中成员i 1集合不存在于另一个集合中。

所以,例如,我有这个基本的类对象

Class Person
    Public Property FirstName As String
End Class

我现在创建了2个列表:

Dim l1 As List(Of Person) = New List(Of Person)()
Dim l2 As List(Of Person) = New List(Of Person)()

Dim p1 As Person = New Person()
p1.FirstName = "andy"
l1.Add(p1)

Dim p2 As Person = New Person()
p2.FirstName = "john"
l1.Add(p2)

Dim p3 As Person = New Person()
p3.FirstName = "david"
l2.Add(p3)

Dim p4 As Person = New Person()
p4.FirstName = "john"
l2.Add(p4)

我想要的是获取包含以下条目的新列表:

andy
david

到目前为止,我有这个:

Dim newList = From c1 In l1, c2In l2
               Where c2.FirstName <> c1.FirstName
               Select c1.FirstName

给了我:

andy
andy
john

我承认我的linq很棒......

2 个答案:

答案 0 :(得分:5)

一种简单的方法是使用All扩展方法:

Dim newList = From c1 In l1
              Where l2.All(Function(c2) c2.FirstName <> c1.FirstName)
              Select c1.FirstName

另一种解决方案可能是使用Except扩展方法:

Dim newList=l1.Select(Function(c1) c1.FirstName).Except(l2.Select(Function(c2) c2.FirstName));

更新

我现在注意到你想要两个列表中的独占元素。您可以连接两个名称列表并稍后应用GroupBy以仅获取一次出现的名称:

Dim newList=l1.Select(Function(c1) c1.FirstName).Concat(l2.Select(Function(c2) c2.FirstName))
           .GroupBy(Function(c) c)
           .Where(Function(g) g.Count()=1)
           .Select(Function(g) g.Key);

答案 1 :(得分:1)

试试这个:

    For Each item As String In List2
        If Not List1.Contains(item) Then
            List1.Add(item)
        End If
    Next

&#39;合并

[FromQuery]