在一个特定的属性比较两个泛型列表 [英] Comparing two generic lists on a specific property

查看:224
本文介绍了在一个特定的属性比较两个泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,"","")

在上面的例子中

结果将包含一个客户,李四,因为标识符 2 是不是在第二个列表。

Result in the above example would contain one customer, Jane Doe, because the identifier 2 wasn't in the second list.

您如何比较这两个名单,其中,T> 的IEnumerable< T> 在.NET 2.0(缺少LINQ)?

How can you compare these two List<T> or any IEnumerable<T> in .NET 2.0 (lacking LINQ)?

推荐答案

下面是C#版本,VB来了不久......

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

...这是VB的翻译。需要注意的是VB不具有匿名函数在.NET2,因此,使用的ForEach 的FindAll 方法会比较笨拙比标准对于每个循环:

...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

这篇关于在一个特定的属性比较两个泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆