按值从列表中删除项目

Tol*_*lox 6 c# class

我有一个类对象列表,并希望删除一个项目,但它不起作用:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

RemoveAt(1)工作并删除ID为1的项目.

我认为删除(A)应该删除值为"A"的项目.但这不起作用.有人可以解释原因吗?什么是按值删除的正确方法?

ast*_*tef 13

从元素的属性值中删除列表的最简单方法:

newPersonList.RemoveAll(p => p.name == "A");
Run Code Online (Sandbox Code Playgroud)

更好的方式是改变Person:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

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

甚至是这样的:

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

  • 他可以使用`newPersonList.RemoveAll(p => p.name =="A")`.您的方法需要扫描列表两次.但更好的方法是覆盖`Person`中的`Equals`或让它实现`IEquatable <Person>`.然后`删除'按预期工作. (3认同)