我正在尝试更新包含可观察集合的对象,该集合包含另一个可观察集合。以下代码有效,但很难看。我怎样才能改善这个?
ProfileBO包含Observable Collection ZoneBOList。 ZoneBOList包含Observable Collection 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);
}
答案 0 :(得分:1)
对我来说,你的整个代码看起来不一致:
在回答这些问题之前,所有这些都可以简化为:
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);
}
}