有没有办法找到列表中的对象的属性使用包含?
-
22-07-2019 - |
题
我是随便我怎么能找出如果一个对象在我的名单已经存在。 我在一个列表中添加“newPerson”(人类的实例),但检查是否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;
}
首先,我想简化/上述优化此丑陋的代码。因此,我认为有关使用包含方法。
List<Person> people = this.GetPeople();
if (people.Contains<Person>(newPerson)) //it doesn't work!
{
MessageBox.Show("This person is already in the party!");
return;
}
上面的第二代码不工作,我认为这是比较对象的引用,而不是对象的内容/属性。
有人这里#1和在链接文本一>在谈论使用实现的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;
}
有没有找到一个List我的对象的属性更小的方法是什么?
解决方案
使用Exists
或Any
使用谓词:
List<Person> people = this.GetPeople();
if (people.Exists(p => p.PersonID == newPerson.PersonID
&& p.PersonName == newPerson.PersonName))
{
MessageBox.Show("This person is already in the party!");
return;
}
这将与.NET 2.0工作(并且可以使用匿名方法被转换为C#2)。越LINQy溶液是Any
:
List<Person> people = this.GetPeople();
if (people.Any(p => p.PersonID == newPerson.PersonID
&& p.PersonName == newPerson.PersonName))
{
MessageBox.Show("This person is already in the party!");
return;
}
其他提示
这听起来像你的Person类应实现 IEquatable <人> 。是的,这是(有点)更多的代码,但你没有要比较2个人对象每次重复。
在包含列表的方法使用由默认对象的Equals方法。所以,如果你正确地贯彻执行IEquatable,你不必通过一个自定义的IEqualityComparer。
不隶属于 StackOverflow