Comparing two generic lists on a specific property

不羁岁月 提交于 2019-12-03 21:52:47

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;
                                               });
                          });
Koeuy Chetra

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!