删除列表中的对象<>在c#
本文关键字:对象 删除列 列表 删除 | 更新日期: 2023-09-27 18:15:47
我有一个控制台应用程序项目,它有一个list
。这包括添加、显示和删除项目的选项,但删除方法不起作用。当我删除一些东西时,应用程序崩溃了。请看看下面我的代码和建议。
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);
}
}
}
}
}
不能在遍历列表时从列表中删除。
一种方法是创建一个你想要删除的东西的列表,然后在你完成迭代后删除它们。
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);
}
实际上,您可以在迭代时从列表中删除,但您必须使用其他循环而不是foreach,并从列表中删除项,例如:
for(int i=0; i<list.Count;i++)
{
if(something)
{
list.Remove(list[i]);
i--;
}
}
在这种情况下,你必须减少'i'变量,以免跳过另一个对象(由于删除列表中的一个)。
我不是说这是一个好的解决方案,而是说这是可能做到的。
如上所述,添加要删除的项是很好的。在LINQ中删除它们而不是在本例中删除foreach循环,如下所示:list.Remove(x=>deleteList.Contains(x));