我可以使用LINQ比较两个集合之间缺少,添加或更新的内容吗 [英] Can I use LINQ to compare what is missing, added or updated between two collections
问题描述
我有以下课程.为了做到这一点,我可以比较一下,我添加了一个Equals方法:
I have the following class. To make it so I could compare I added an Equals method:
public ObjectiveDetail()
public int ObjectiveDetailId { get; set; }
public int Number { get; set; }
public string Text { get; set; }
public override bool Equals(object obj)
{
return this.Equals(obj as ObjectiveDetail);
}
public bool Equals(ObjectiveDetail other)
{
if (other == null)
return false;
return this.Number.Equals(other.Number) &&
(
this.Text == other.Text ||
this.Text != null &&
this.Text.Equals(other.Text)
);
}
}
我有两个ICollection集合:
I have two ICollection collections:
ICollection<ObjectiveDetail> _obj1; // Reference
ICollection<ObjectiveDetail> _obj2; // May have more, less or different objectDetails from the reference.
集合的通用tfield是ObjectiveDetailId.有没有一种方法可以使用三个LINQ表达式来创建:
The common tfield with the collections is ObjectiveDetailId. Is there a way I can use three LINQ expressions to create:
- _obj2中而不是_obj1中的行的集合
- _obj1中而不是_obj2中的行的集合
- _obj1和_obj2之间不同的行的集合
请注意,这类似于我之前问的另一个问题,但是我认为现在添加了Equals方法,这有点简单.应该这样做吗?
Note this is similar to another question I asked earlier but I think this is a bit simpler now I have added the Equals method. uld do this?
推荐答案
You can use Except
to subtract sets:
var in2butNot1 = _obj2.Except(_obj1);
var in1butNot2 = _obj1.Except(_obj2);
但是,这可能并不是您想要得到的,因为已更改"的对象将被视为彼此不相等".
However, this may not be what you are looking to get, because objects that have "changed" will be treated as simply "not equal" to each other.
看来您的对象有一个ID
字段.您可以在该ID
上对对象进行排序,然后遍历两个集合,就好像您正在生成合并一样.这样,您就可以使用简单的if
链来检测插入,更新和删除.
It appears that your objects have an ID
field. You can order the objects on that ID
, and then traverse both collections as if you were producing a merge. This would let you detect insertions, updates, and deletions with a straightforward chain of if
s.
您还可以使用ID来确定什么是共同的,什么是改变的:
You can also use IDs to decide what's common and what's changed:
var ids1 = new HashSet<int>(_obj1.Select(o => o.ObjectiveDetailId));
var ids2 = new HashSet<int>(_obj2.Select(o => o.ObjectiveDetailId));
var in2butNot1 = _obj2.Where(o => !ids1.Contains(o.ObjectiveDetailId));
var in1butNot2 = _obj1.Where(o => !ids2.Contains(o.ObjectiveDetailId));
这篇关于我可以使用LINQ比较两个集合之间缺少,添加或更新的内容吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!