Reputation: 55
I have a console application project which has a list
. This includes options of adding, displaying and deleting items from it but the deleting method is not working. Application crashes when i delete something. Please have a look at my code below and advise.
class Program
{
public List<CV_details> list = new List<CV_details>();
static void Main()
{
Program p = new Program();
int choice;
do
{
p.menu();
Console.Write("Enter Choice : ");
choice = Convert.ToInt32(Console.ReadLine());
if (choice == 3)
{
Console.Clear();
p.modify();
break;
}
} while (choice != 4);
}
void modify()
{
Console.Write("Enter ID you want to modify : ");
int id = Convert.ToInt32(Console.ReadLine());
var per = new CV_details();
foreach (var person in list)
{
if (person.getID() == id)
{
Console.WriteLine("Serial No. : " + person.getID());
Console.WriteLine("Name : {0} {1}", person.getFname(), person.getlname());
Console.WriteLine("Age : {0}", person.getAge());
Console.WriteLine("Degree : {0}", person.getdegree());
Console.WriteLine();
Console.WriteLine("1) To Delete CV");
Console.WriteLine("2) To Update");
int n;
Console.WriteLine("Enter Choice :");
n = Int32.Parse(Console.ReadLine());
if (n == 1)
{
list.Remove(person);
}
}
}
}
}
Upvotes: 2
Views: 191
Reputation: 154
Practically you can delete from list while iterating, but you have to use some other loop than foreach and remove item from the list like:
for(int i=0; i<list.Count;i++)
{
if(something)
{
list.Remove(list[i]);
i--;
}
}
In this case you have to decrease also the 'i' variable not to skip another object (due to removing one of the list).
I am not saying it`s a good solution, but that it is possible to do.
Adding items to remove, as mentioned above, is nice. Deleting them in LINQ instead of foreach loop in this case would look like:
list.Remove(x=>deleteList.Contains(x));
Upvotes: 0
Reputation: 150108
You cannot remove from a list while iterating through it.
One approach is to create a list of things that you want to remove, and then remove them after you are done iterating.
List<CV_details> deleteList = new List<CV_details>();
foreach (var person in list){
if (person.getID()==id)
{
//...
n = Int32.Parse(Console.ReadLine());
if (n == 1)
{
deleteList.Add(person);
}
}
}
foreach (var del in deleteList)
{
list.Remove(del);
}
You can do this with fewer lines of code using Linq.
Upvotes: 4