Comparing two generic lists on a specific property
I'm using VB.NET with .NET 2.0开发者_运维问答.
I have two lists, and I want to compare the lists on a specific property in the object, not the object as a whole, and create a new list that contains objects that are in one list, but not the other.
myList1.Add(New Customer(1,"John","Doe")
myList1.Add(New Customer(2,"Jane","Doe")
myList2.Add(New Customer(1,"","")
Result in the above example would contain one customer, Jane Doe, because the identifier 2
wasn't in the second list.
How can you compare these two List<T>
or any IEnumerable<T>
in .NET 2.0 (lacking LINQ)?
Here's the C# version, VB coming up shortly...
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); });
...and here's the VB translation. Note that VB doesn't have anonymous functions in .NET2, so using the ForEach
and FindAll
methods would be more clumsy than standard For Each
loops:
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
This is possible in c# 2.0.
List<Customer> results = list1.FindAll(delegate(Customer customer)
{
return list2.Exists(delegate(Customer customer2)
{
return customer.ID == customer2.ID;
});
});
I want to share my function to compare two list of objects:
Code:
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
Example:
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
精彩评论