简体   繁体   中英

Remove item from list by value

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?

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"));

So you want .net magically to guess that by "A" string you mean field name ? How is it supposed to derive it?

I would suggest you use a Dictionary if you want to operate things by their key (name in this case):

var dict = new Dictionary<string, Person>() {
   {"A", new Person("A")}
}

//and later

dict.Remove("A");

You have not declared A. To do newPersonList.Remove(A);

You have to declare an object Person A and add it to newPersonList

Person A = new Person("A");
newPersonList.Add(A);

Like other said "What is A ?". If it would be a variable that contains a Person that this will work.

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

    newPersonList.Remove(A);
}

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