![](/img/trans.png)
[英]How to efficiently select a range in an observable collection into another observable collection
[英]how can I update this observable collection more efficiently?
我正在尝试更新一个包含可观察集合的对象,该对象包含另一个可观察集合。 以下代码有效,但是很丑陋。 我该如何改善?
ProfileBO包含Observable Collection ZoneBOList。 ZoneBOList包含Observable集合ZoneMonitorBOList。 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);
}
对我来说,您的整个代码看起来不一致:
在您回答这个问题之前,所有这些都可以简化为:
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.