How to delete an item from a generic list

后端 未结 9 462
死守一世寂寞
死守一世寂寞 2020-12-31 05:51

I have a generic list

How do I remove an item?

EX:

Class Student
{
    private number;
    public Number
    {
        get( return number;)
          


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 06:39


    From your comments I conclude that you read student name from input and you need to remove student with given name.

    class Student {
        public string Name { get; set; }
        public int Number { get; set; }
    
        public Student (string name, int number)
        {
            Name = name;
            Number = number;
        }
    }
    
    
    var students = new List {
        new Student ("Daniel", 10),
        new Student ("Mike", 20),
        new Student ("Ashley", 42)
    };
    
    var nameToRemove = Console.ReadLine ();
    students.RemoveAll (s => s.Name == nameToRemove); // remove by condition
    

    Note that this will remove all students with given name.

    If you need to remove the first student found by name, first use First method to find him, and then call Remove for the instance:

    var firstMatch = students.First (s => s.Name == nameToRemove);
    students.Remove (firstMatch);
    

    If you want to ensure there is only one student with given name before removing him, use Single in a similar fashion:

    var onlyMatch = students.Single (s => s.Name == nameToRemove);
    students.Remove (onlyMatch);
    

    Note that Single call fails if there is not exactly one item matching the predicate.

提交回复
热议问题