The code throws an error with reason as we easily see.
Error:{"Collection was modified; enumeration operation may not execute."}
But there must be a way to do that, with foreach (not for), with using List<>. Please do not tell me Deep Copy methods like making
var cloneList = NumberList.ToList()
and removing item from it. Because if we have 1 million elements, we will make it 2 million for removing etc. I don't need this.
The code snippet is here;
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
var numberList = new List<int>();
numberList.AddRange(new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
var totalNumber = 0;
foreach (var item in numberList)
{
totalNumber += item;
if (item == 5)
{
numberList.Remove(item);
}
}
return View(totalNumber);
}
}
Please help me about this brain burner code snippet..
Thank you.
UPDATE : The question is not about getting Sum()
of the List elements at the final point. The core of question is, how to remove item from list while foreach looping.