c# - 比较大量对象

标签 c# asp.net-mvc-3

我有一个表单,其中包含一次全部更新的对象列表。在 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/

相关文章:

c# - 确保解决方案中的项目来自同一个 TFS 分支

c# - 从 C# 说明文件打开 Excel 电子表格时引发异常,其他用户正在使用该文件

c# - 是否有用于 Visual Studio 的断点插件?

asp.net-mvc-3 - 如何打印未映射的值

asp.net-mvc-3 - 继承自 HtmlHelper 而不是扩展它

asp.net-mvc-3 - 使用 ViewData 将字符串从 Controller 传递到 ASP.NET MVC3 中的 View

c# - 使用 CSLA 在 C# .NET 中禁用文本框

c# - Server.TransferRequest() 和 http 状态码

c# - 如何在 AutoMapper 中处理自定义属性

c# - 即使提供了显式值,HtmlHelper.TextBox 也会使用模型值