Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from list by value

Tags:

c#

class

I have a list of class objects and want to remove one item but it doesn´t work:

    class Person
    {
        public string name; 
        public Person(string s)
        {
            this.name = s;
        }
    }

    void ABC()
    {
        List<Person> newPersonList = new List<Person>();
        newPersonList.Add(new Person("A"));
        newPersonList.Add(new Person("B"));
        newPersonList.Add(new Person("C"));

        newPersonList.Remove(A);
        newPersonList.RemoveAt(1);
    }

RemoveAt(1) works and deletes item with the ID 1.

I think Remove(A) should delete the item with the value "A". But this is not working. Can someone explain why? And what is the right way to delete by value?

like image 900
Tolox Avatar asked Aug 13 '15 13:08

Tolox


People also ask

How do you remove an entry from a list by value?

The remove() method is one of the ways you can remove elements from a list in Python. The remove() method removes an item from a list by its value and not by its index number.

How do I remove an item from a string in Python list?

Use list. remove() to remove a string from a list. Call list. remove(x) to remove the first occurrence of x in the list.


1 Answers

Easiest way to remove from list by element's property value:

newPersonList.RemoveAll(p => p.name == "A");

Nicer way would be to change Person like that:

class Person : IEquatable<Person>
{
    public readonly string Name;
    public Person(string name)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("name");
        Name = name;
    }
    public static implicit operator string(Person p)
    {
        return p.Name;
    }
    public static implicit operator Person(string name)
    {
        return new Person(name);
    }
    public bool Equals(Person other)
    {
        return Name.Equals(other.Name);
    }
}

And then use it like that:

var newPersonList = new List<Person>
{
    new Person("A"),
    new Person("B"),
    new Person("C")
};
newPersonList.Remove("A");

Or even like that:

var newPersonList = new List<Person> { "A", "B", "C" };
newPersonList.Remove(new Person("A"));
like image 53
astef Avatar answered Sep 21 '22 00:09

astef