比较特定属性上的两个通用列表

时间:2010-07-09 20:36:02

标签: .net vb.net generics .net-2.0 list

我正在使用VB.NET和.NET 2.0。

我有两个列表,我想比较对象中特定属性的列表,而不是整个对象,并创建一个新列表,其中包含一个列表中的对象,而不是另一个列表中的对象。 / p>

myList1.Add(New Customer(1,"John","Doe")
myList1.Add(New Customer(2,"Jane","Doe")

myList2.Add(New Customer(1,"","")

以上示例中的结果将包含一个客户 Jane Doe ,因为标识符2不在第二个列表中。

如何在.NET 2.0(缺少LINQ)中比较这两个List<T>或任何IEnumerable<T>

3 个答案:

答案 0 :(得分:3)

这是C#版本,VB很快就会出现......

Dictionary<int, bool> idMap = new Dictionary<int, bool>();
myList2.ForEach(delegate(Customer c) { idMap[c.Id] = true; });

List<Customer> myList3 = myList1.FindAll(
    delegate(Customer c) { return !idMap.ContainsKey(c.Id); });

......这是VB的翻译。请注意,VB在.NET2中没有匿名函数,因此使用ForEachFindAll方法比标准For Each循环更笨拙:

Dim c As Customer

Dim idMap As New Dictionary(Of Integer, Boolean)
For Each c In myList2
    idMap.Item(c.Id) = True
Next

Dim myList3 As New List(Of Customer)
For Each c In myList1
    If Not idMap.ContainsKey(c.Id) Then
        myList3.Add(c)
    End If
Next

答案 1 :(得分:0)

这在c#2.0中是可行的。

List<Customer> results = list1.FindAll(delegate(Customer customer)
                          {
                              return list2.Exists(delegate(Customer customer2)
                                               {
                                                   return customer.ID == customer2.ID;
                                               });
                          });

答案 2 :(得分:0)

我想分享我的功能来比较两个对象列表:

代码:

Public Function CompareTwoLists(ByVal NewList As List(Of Object), ByVal OldList As List(Of Object))
                If NewList IsNot Nothing AndAlso OldList IsNot Nothing Then
                    If NewList.Count <> OldList.Count Then
                        Return False
                    End If
                    For i As Integer = 0 To NewList.Count - 1
                        If Comparer.Equals(NewList(i), OldList(i)) = False Then
                            Return False
                        End If
                    Next
                End If
                Return True
            End Function

示例:

Dim NewList as new list (of string) from{"0","1","2","3"} 
Dim OldList as new list (of string) from{"0","1","2","3"} 
messagebox.show(CompareTwoLists(NewList,OldList)) 'return true 

Dim NewList as new list (of string) from{"0","1","2","4"} 
Dim OldList as new list (of string) from{"0","1","2","3"} 
messagebox.show(CompareTwoLists(NewList,OldList)) 'return false