c# - Element not getting added in List -


i have class called estimate , has following field , property:

private ilist<routeinformation> _routematrix; public virtual ilist<routeinformation> routematrix {         {         if (_routematrix != null && _routematrix.count > 0)         {             var routematrix = _routematrix.tolist();             routematrix =                     routematrix.orderby(tm => tm.level.leveltype).thenby(tm => tm.level.levelvalue).tolist();             return routematrix;         }         else return _routematrix;     }     set { _routematrix = value; } } 

so, in getter method, sorting _routematrix level type , level value , returning sorted list.

in 1 of programs, have following code:

public void saveapprovers(string[] approvers) {     int = 1;     foreach (var approver in approvers)     {         var role = repository.get<role>(long.parse(approver));         var level = new models.level         {             leveltype = leveltype.approver,             levelvalue = (levelvalue)i,             role = role         };         repository.save(level);         var routeinformation = new models.routeinformation         {             level = level,             routeobjecttype = routeobjecttype.estimate,             routeobjectid = _estimate.id         };         repository.save(routeinformation);         _estimate.routematrix.add(routeinformation); // <--- problem here         repository.save(_estimate);         i++;     } } 

the problem that, if there multiple approvers (i.e: length of approvers array greater 1, first routeinformation added in routematrix. don't know happen rest of them, add method doesn't give error.

earlier, routematrix public field. problem started occuring after made private , encapsulated in public property.

your get member returns different list, add temporary list.

  {     if (_routematrix != null && _routematrix.count > 0)     {         var routematrix = _routematrix.tolist(); // tolist creates _copy_ of list         ...         return routematrix;     }     else return _routematrix;  }   .....   _estimate.routematrix.add(routeinformation);   // add result of tolist() 

i think moral here not make getters complicated. sorting wasted effort anyway when want add().

also, bad things happen when _routematrix == null. may not happen if (_routematrix != null && ...) part misleading noise.


Comments