在 NHibernate 中处理具有父子关系的集合
当我处理两个列表时,我在找出要添加、更新和删除哪些子项时遇到问题,一个列表包含旧子项(来自数据库),另一个列表包含修改后的子项(来自用户输入)。
目前我必须循环遍历列表并进行比较以找出差异。
有谁知道更好的方法来做到这一点而不必循环列表?
I'm having a problem with finding out which children to add, update and delete when I'm dealing with two lists one with the old chidren (from db) and the other list with the modified children (from user input).
Currently I have to loop through the lists and compare to find the difference.
Does anyone know of a better way of doing this without having to loop through the lists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IEnumerable.Except 扩展方法非常适合此目的。在大多数情况下,您需要使用接受
IEqualityComparer
的重载来按标识进行比较,除非您已在对象中仔细重写了 Equals 和 GetHashCode。给定的
代码是:
ToArray()
调用在那里,以便您可以在迭代添加和删除列表时对原始列表进行更改。编辑:下面是两个实用程序类,可以使此操作变得容易。用法是
The IEnumerable.Except extension method is perfect for this. In most cases you will want to use the overload that accepts an
IEqualityComparer<T>
to compare by identity, unless you have carefully overridden Equals and GetHashCode in your objects.Given
The code is:
The
ToArray()
calls are there so that you can make changes to the original list while iterating the add and remove lists.Edit: Below are two utility classes that make this operation easy. Usage is