【发布时间】:2011-07-19 05:36:38
【问题描述】:
我有两个实体列表。想象一下 list1 是远程的,而 list2 是本地的 - list1 是在过去某个时间创建的,而 list2 刚刚生成。
我想比较两个列表,按 .id 进行匹配,并仅比较每个元素的 .flag 属性。在 .flag 属性不同的地方,我想选择较旧的元素,但使用 list2 中的 .flag 属性(新列表)。
下面的示例显示了如何仅选择 list1 中不同的实体。如何从 list1 中选择不同的实体,但使用 list2 实体中的 .flag 属性。
注意:我不想 select new SomeEntity(){} 整个 SomeEntity 类,因为在真正的问题中,我正在使用的类有很多属性。
class SomeEntity
{
public int id;
public bool flag;
public int some_value = -1;
}
// Setup the test
List<SomeEntity> list1 = new List<SomeEntity>();
List<SomeEntity> list2 = new List<SomeEntity>();
for (int i = 0; i < 10; i++ )
{
list1.Add(new SomeEntity() { id = i, flag = true, some_value = i * 100 });
list2.Add(new SomeEntity() { id = i, flag = true, });
}
// Toggle some flags
list1[3].flag = false;
list2[7].flag = false;
// Now find the entities that have changed and need updating
var items_to_update = from x in list1
join y in list2 on x.id equals y.id
where x.flag != y.flag
select x;
【问题讨论】: