简体   繁体   中英

How to delete an item from a generic list

I have a generic list

How do I remove an item?

EX:

Class Student
{
    private number;
    public Number
    {
        get( return number;)
        set( number = value;)
    }

    private name;
    public Name
    {
        get( return name;)
        set( name = value;)
    }

    main()
    {
        static List<student> = new list<student>();

        list.remove...???
    }
}

Well, there is nothing to remove because your list is empty (you also didn't give it an identifier, so your code won't compile). You can use the Remove(T item) or RemoveAt(int index) to remove an object or the object at a specified index respectively (once it actually contains something).

Contrived code sample:

void Main(...)
{
    var list = new List<Student>();
    Student s = new Student(...);
    list.Add(s);

    list.Remove(s); //removes 's' if it is in the list based on the result of the .Equals method

    list.RemoveAt(0); //removes the item at index 0, use the first example if possible/appropriate
}


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<Student> {
    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.

List<Student> students = new List<Student>();
students.Add(new Student {StudentId = 1, StudentName = "Bob",});
students.RemoveAt(0); //Removes the 1st element, will crash if there are no entries

OR to remove a known Student.

//Find a Single Student in the List.
Student s = students.Where(s => s.StudentId == myStudentId).Single();
//Remove that student from the list.
students.Remove(s);

int count=queue.Count;

        while(count>0)
        {
            HttpQueueItem item = queue[0];
            /// If post succeeded..
            if (snd.IsNotExceedsAcceptedLeadsPerDayLimit(item.DataSaleID, item.AcceptedLeadsPerDayLimit) && snd.PostRecord(item.DataSaleDetailID, item.PostString, item.duplicateCheckHours, item.Username, item.Password, item.successRegex))
            {
                if (item.WaitTime > 0)
                    Thread.Sleep(item.WaitTime);
                queue.Remove(item);
            }
                ///If Exceeds Accepted leads per day limit by DataSale..
            else if (!snd.IsNotExceedsAcceptedLeadsPerDayLimit(item.DataSaleID, item.AcceptedLeadsPerDayLimit))
            {
                queue.RemoveAll(obj => obj.DataSaleID == item.DataSaleID);
            }
                /// If Post failed..
            else //if (!snd.PostRecord(item.DataSaleDetailID, item.PostString, item.duplicateCheckHours, item.Username, item.Password, item.successRegex))
            {
                queue.Remove(item);
            }
            count = queue.Count;
        }

To delete a row or record from generic list in grid view, just write this code-

List<Address> people = new List<Address>();
Address t = new Address();
people.RemoveAt(e.RowIndex);
grdShow.EditIndex = -1;
grdShow.DataSource = people;
grdShow.DataBind();

Well, you didn't give your list a name, and some of your syntax is wonky.

void main()
{
   static List<Student> studentList = new List<Student>();
}

// later
void deleteFromStudents(Student studentToDelete)
{
   studentList.Remove(studentToDelete);
}

There are more remove functions detailed here: C# List Remove Methods

试试linq:

  var _resultList = list.Where(a=>a.Name != nameToRemove).Select(a=>a);

I made a program that contains 7 cards, then shuffle and I hope to take in order to help them

class Program
{

    static void Main(string[] args)
    {
        Random random = new Random(); 
        var cards = new List<string>();
        //CARDS VECRTOR
        String[] listas = new String[] { "Card 1", "Card 2", "Card 3", "Card 4", "Card 5", "Card 6", "Card 7"};


        for (int i = 0; i<= cards.Count; i++)
        {

            int number = random.Next(0, 7); //Random number 0--->7


            for (int j = 0; j <=6; j++)
            {
                if (cards.Contains(listas[number])) // NO REPEAT SHUFFLE
                {

                    number = random.Next(0, 7); //AGAIN RANDOM

                }
                else
                {
                    cards.Add(listas[number]); //ADD CARD
                }
            }

        }

        Console.WriteLine(" LIST CARDS");

        foreach (var card in cards)
        {
            Console.Write(card + " ,");


        }

        Console.WriteLine("Total Cards: "+cards.Count);

        //REMOVE

        for (int k = 0; k <=6; k++)
        {
           // salmons.RemoveAt(k);
            Console.WriteLine("I take the card: "+cards.ElementAt(k));
            cards.RemoveAt(k); //REMOVE CARD
            cards.Insert(k,"Card Taken"); //REPLACE INDEX
            foreach (var card in cards)
            {
                Console.Write(card + " " + "\n");

            }


        }


        Console.Read(); //just pause

    }



}

Maybe you can use a Dictionary<string, Student> instead of the List<Student> .

When you add a Student, add its ID or Name or whatever can uniquely identify it. Then you can simply call myStudents.Remove(myStudentId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM