我在徘徊如何找出我的列表中是否已经存在一个对象。我在列表中添加“newPerson”(Person 类的实例),但检查列表中是否存在 newPerson 内容/属性。
这件作品很好:
List<Person> people = this.GetPeople();
if (people.Find(p => p.PersonID == newPerson.PersonID
&& p.PersonName == newPerson.PersonName) != null)
{
MessageBox.Show("This person is already in the party!");
return;
}
首先,我想简化/优化上面这段丑陋的代码。所以我想到了使用 Contains 方法。
List<Person> people = this.GetPeople();
if (people.Contains<Person>(newPerson)) //it doesn't work!
{
MessageBox.Show("This person is already in the party!");
return;
}
上面的第二个代码不起作用,我认为它是在比较对象引用而不是对象内容/属性。
Stackoverflow 和链接文本中的某个人正在谈论使用实现 IEqualityComparer 的类。我试了一下,但现在代码更大了!就像是:
public class PersonComparer : IEqualityComparer<Person>
{
// Products are equal if their names and i numbers are equal.
public bool Equals(Person x, Person y)
{
// Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
// Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
// Check whether the products' properties are equal.
return x.PersonID == y.PersonID && x.PersonName == y. PersonName;
}
// If Equals() returns true for a pair of objects,
// GetHashCode must return the same value for these objects.
public int GetHashCode(Person p)
{
// Check whether the object is null.
if (Object.ReferenceEquals(p, null)) return 0;
// Get the hash code for the Name field if it is not null.
int hashPersonName = p.PersonName == null ? 0 : p.PersonName.GetHashCode();
int hashPersonID = i.PersonID.GetHashCode();
// Calculate the hash code for the i.
return hashPersonName ^ hashPersonID;
}
}
并使用这个比较器:
PersonComparer comparer = new PersonComparer();
if (people.Contains<Person>(newPerson, comparer))
{
MessageBox.Show("This person is already in the party.");
return;
}
有没有更小的方法可以在列表中找到我的对象的属性?