2010-07-09 66 views
0

我在.NET 2.0中使用VB.NET。比较特定属性上的两个通用列表

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

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

这里的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 
0

这是可能在C#2.0。

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

是否有可能用VB.NET(。 NET 2.0)? – 2010-07-12 14:16:23

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