Reputation: 406
I am using below code to loop through items and adding items to list.But While adding items to list, old items in list are getting replaced with new items . How can I avoid items replacement in list .
var finalMenuList=new List<IMenu>();
foreach(var menuSKU in iMenuSKUList)
{
var menu = new IMenuSKU();
menu=iMenuList.Where(a => a.Id == menuSKU.Id).ToList()[0];
var menuSpecs=new List<IMenuMapping>() ;
menuSpecs= iMenuCompleteSKUList.Where(a => a.Id == menuSKU.Id ).ToList();
var media = new List<IMenuMedia>();
media = iMediaList.Where(a => a.Id == menuSKU.Id).ToList();
menu.MenuMappings = null;
menu.MenuMappings = menuSpecs;
menu.MenuMedias = null;
menu.MenuMedias = media;
finalMenuList.Add(menu);
}
Upvotes: 2
Views: 1452
Reputation: 406
Issue has been resolved with below code
foreach(var menuSKU in iMenuSKUList)
{
var menu = new IMenuSKU();
menu=iMenuList.Where(a => a.Id == menuSKU.Id).ToList()[0];
var menuSpecs=new List<IMenuMapping>() ;
menuSpecs= iMenuCompleteSKUList.Where(a => a.Id == menuSKU.Id ).ToList();
var media = new List<IMenuMedia>();
media = iMediaList.Where(a => a.Id == menuSKU.Id).ToList();
menu.MenuMappings = null;
menu.MenuMappings = menuSpecs;
menu.MenuMedias = null;
menu.MenuMedias = media;
// issue has been resolved by creating new instance of object and reassigning it's properties with values as below and finally storing it in list.
var finalList = new IMenuSKU
{
MenuMappings = menu.MenuMappings,
MenuMedias = menu.MenuMedias,
//bind remaining properties here
};
finalMenuList.Add(finalList);
}
Upvotes: 1
Reputation: 3019
The main problem is, that you modify object from original List before you add it to final List.
menu=iMenuList.Where(a => a.Id == menuSKU.Id).ToList()[0];
Here the menu
object is taken from iMenuList
and then modified
menu.MenuMappings = null;
That causes your objects from original List to be modified. If you want to change object that is passed to finalList, but don't want to modify one that is stored in original List than you must work with copy the new object (clone).
Upvotes: 2
Reputation: 5
You can override Equals method in your class to return something unique for each of objects. This will avoid replacement of objects.
Upvotes: -1