简体   繁体   English

如何更有效地更新此可观察的集合?

[英]how can I update this observable collection more efficiently?

I am trying to update an object that contains an observable collection that contains another observable collection. 我正在尝试更新一个包含可观察集合的对象,该对象包含另一个可观察集合。 The following code works, but it is ugly. 以下代码有效,但是很丑陋。 How can I improve this? 我该如何改善?

ProfileBO contains the Observable Collection ZoneBOList. ProfileBO包含Observable Collection ZoneBOList。 ZoneBOList contains the Observable Collection ZoneMonitorBOList. ZoneBOList包含Observable集合ZoneMonitorBOList。 ZoneMonitorBOList IS the object collection for the object I am trying to add. ZoneMonitorBOList是我要添加的对象的对象集合。

while (reader.Read())
{
   ZoneMonitorBO zoneMonitorBO = new ZoneMonitorBO();
   zoneMonitorBO.ZoneId = (int)reader["zone_id"];
   zoneMonitorBO.MonitorId = (int)reader["monitor_id"];

   ZoneBO zoneBO = new ZoneBO();
   //Pluck off the object from the observable collection that we need to update
   zoneBO = profileBO.ZoneBOList.FirstOrDefault(i => i.ZoneID == zoneMonitorBO.ZoneId);
   //Add the business object to the observable collection of the observable collection 
   zoneBO.ZoneMonitorBOList.Add(zoneMonitorBO);
   //remove the old object                        
   profileBO.ZoneBOList.Remove(profileBO.ZoneBOList.Where(c => c.ZoneID == zoneMonitorBO.ZoneId).Single());
   //add the updated object to the 'parent' observable collection
   profileBO.ZoneBOList.Add(zoneBO);
}

To me your entire code looks inconsistent: 对我来说,您的整个代码看起来不一致:

  • Why you creating and reassign ZoneBO? 为什么创建和重新分配ZoneBO?
  • Why you looking for it second time? 为什么第二次寻找它? You do understand that you add the same object you modified then deleted by reference? 您知道您添加了相同的对象,然后通过引用将其删除了吗?
  • Why you need to remove it and add again into collection? 为什么需要将其删除并再次添加到集合中?
  • What if FirstOrDefault returns null and you get an exception? 如果FirstOrDefault返回null并得到异常怎么办?

Until you answer for this questions, all this can be simplified to just this: 在您回答这个问题之前,所有这些都可以简化为:

while (reader.Read())
{
   var zoneMonitorBO = new ZoneMonitorBO();
   zoneMonitorBO.ZoneId = (int)reader["zone_id"];
   zoneMonitorBO.MonitorId = (int)reader["monitor_id"];

   var zoneBO = profileBO.ZoneBOList.FirstOrDefault(i => i.ZoneId == zoneMonitorBO.ZoneId);
   if(zoneBO != null)
   {
       zoneBO.ZoneMonitorBOList.Add(zoneMonitorBO);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM