[英]Remove item from list by value
我有一個類對象列表,想要刪除一個項目,但是它不起作用:
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)工作並刪除ID為1的項目。
我認為Remove(A)應該刪除值為“ A”的項目。 但這是行不通的。 有人可以解釋為什么嗎? 而按值刪除的正確方法是什么?
按元素的屬性值從列表中刪除的最簡單方法:
newPersonList.RemoveAll(p => p.name == "A");
更好的方法是像這樣更改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);
}
}
然后像這樣使用它:
var newPersonList = new List<Person>
{
new Person("A"),
new Person("B"),
new Person("C")
};
newPersonList.Remove("A");
甚至像這樣:
var newPersonList = new List<Person> { "A", "B", "C" };
newPersonList.Remove(new Person("A"));
因此,您想讓.net神奇地猜測,用"A"
字符串表示字段name
什么? 應該如何推導它?
如果您想通過它們的鍵(在這種情況下為名稱)操作事物,我建議您使用字典:
var dict = new Dictionary<string, Person>() {
{"A", new Person("A")}
}
//and later
dict.Remove("A");
您尚未聲明A。要做newPersonList.Remove(A);
您必須聲明一個對象Person A並將其添加到newPersonList
Person A = new Person("A");
newPersonList.Add(A);
就像其他人說的“什么是A
?”。 如果它將是一個包含Person
的變量,那么它將起作用。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.