views:

103

answers:

2

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)?

+2  A: 

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
LukeH
A: 

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;
                                               });
                          });
jdot
Is it possible with VB.NET (.NET 2.0)?
Ek0nomik