我有一个表单,其中包含一次全部更新的对象列表。在 Controller 中,嵌套循环将每个模型与其他模型进行比较,以便确定哪些对象已更新,哪些是新对象。
foreach(var x in formObject)
{
foreach(var y in dbObject)
{
if(x.id == y.id)
{
//compare each property and notify user of change if different
}
}
}
考虑到大量对象和服务器的速度,这需要花费大量时间。
这样做有更好的做法吗?在遍历所有对象之前确定哪些对象已更新的某种方法?还是更高效的循环?
最佳答案
您可以在 Linq 中使用联接:
var differences =
from x in formObject
join y in dbObject on x.id equals y.id
where ( /* compare each property */ )
select new { /* what do you want to tell the user */ };
当然,如果没有关于循环中内容的更多信息,那只是我能提供的所有代码。
流利的语法是:
var differences =
formObject.Join(dbObject, x => x.id, y => y.id, (x, y) => new { x, y })
.Where(p => /* compare properties of p.x and p.y */)
.Select(p => new { /* what do you want to tell the user */ });
关于c# - 比较大量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19942275/