contains를 사용하여 목록에서 객체의 속성을 찾는 방법이 있습니까?
-
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;
}
위의 두 번째 코드는 작동하지 않으며 객체 내용 / 속성이 아니라 객체 참조를 비교한다고 생각합니다.
여기 STACKOVERFLOW와 IN의 누군가 링크 텍스트 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;
}
목록에서 내 객체의 속성을 찾는 작은 방법이 있습니까?
해결책
사용 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;
}
다른 팁
개인 수업이 구현 해야하는 것처럼 들립니다 iquationableu003CPerson>. 예, 더 많은 코드이지만, 두 사람 객체를 비교할 때마다 반복 할 필요는 없습니다.
목록의 포함 메소드는 기본적으로 객체의 평등 메소드를 사용합니다. 따라서 iquateable을 올바르게 구현하면 사용자 정의 iequalitycomparer를 통과 할 필요가 없습니다.
제휴하지 않습니다 StackOverflow