assign custom list by value memory allocation in c# list object assignment issue
Pergunta
objTempList = objParentList;
foreach (var item in objTempList)
{
objChildList = objList.AsQueryable()
.Where(x => x._parentId == item.filedbid)
.ToList<FileObjectView>();
if (objChildList != null)
{
foreach (var child in objChildList)
{
objParentList.Add(child);
}
}
}
Above is my code, problem is the assignment of objTempList = objParentList
objParentList
has 10 rows which are assigned to objTempList
now in next step when i am doing foreach
and adding more rows in objParentList
its automaticaly reflecting in list objTempList
and my loop is giving error message.
Solução
You should separate list instances to avoid this error
objTempList = objParentList.ToList();
foreach (var item in objTempList)
{
objChildList = objList.AsQueryable().Where(x => x._parentId == item.filedbid).ToList();
foreach (var child in objChildList)
objParentList.Add(child);
}
Outras dicas
If you want to assign the contents of objParentList
to objTempList
without inadvertently modifying objTempList
inside your foreach loop, then you need to create a new instance of of objParentList
and assign that to objTempList
.
That way, adding list items to the parent list inside of the loop will not throw an exception since you assigned a copy of the original to objTempList
and not a reference. For example:
objTempList = new List<T>(objParentList);