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?
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.
Use list. remove() to remove a string from a list. Call list. remove(x) to remove the first occurrence of x in the list.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With