在一个特定的属性比较两个泛型列表

我使用VB.NET使用.NET 2.0。

我有两个列表,我想在一个特定的属性比较列表中的对象,而不是对象作为一个整体,并创建一个新的列表,其中包含了在一个列表对象,而不是其他。

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

在上面的例子中导致将包含一个客户,Jane Doe的 ,因为识别符2是不是在第二列表。

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

--------------解决方案-------------

下面是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

这是可能在C#2.0。

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

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

码:

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

分类:。净 时间:2015-03-15 人气:3
分享到:

相关文章

Copyright (C) 55228885.com, All Rights Reserved.

55228885 版权所有 京ICP备15002868号

processed in 0.819 (s). 10 q(s)