免责声明:此解决方案并未专门处理BaseCode
不同/相同位置的相同问题;您在要求中没有提到任何有关此的内容。
IEqualityComparer<T>
路线
这里的重要部分是 和的IEqualityComparer<T>
实现:Person
Location
class Program
{
static void Main(string[] args)
{
var p1 = new Person {Name ="John", BaseCode="AA12", Locations = new List<Location>
{
new Location { Name = "India" },
new Location { Name = "USA" }
}};
var p2 = new Person {Name ="John", BaseCode="AA13", Locations = new List<Location>
{
new Location { Name = "India" },
new Location { Name = "USA" }
}};
var p3 = new Person {Name ="John", BaseCode="AA14", Locations = new List<Location>
{
new Location { Name = "India" },
new Location { Name = "UK" }
}};
var persons = new List<Person> { p1, p2, p3 };
// Will not return p2.
var distinctPersons = persons.Distinct(new PersonComparer()).ToList();
Console.ReadLine();
}
}
public class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (x == null || y == null)
return false;
bool samePerson = x.Name == y.Name;
bool sameLocations = !x.Locations
.Except(y.Locations, new LocationComparer())
.Any();
return samePerson && sameLocations;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
public class LocationComparer : IEqualityComparer<Location>
{
public bool Equals(Location x, Location y)
{
if (x == null || y == null)
return false;
return x.Name == y.Name;
}
public int GetHashCode(Location obj)
{
return obj.Name.GetHashCode();
}
}
使用提供PersonComparer
的 linqExcept
扩展LocationComparer
来生成两个位置列表之间的差异列表。
然后PersonComparer
输入 linqDistinct
方法。
IEquatable<T>
路线
如果您需要以不同BaseCode
的方式计算成为“匹配”,我认为这条路线不会奏效,因为没有给您区分价值观的机会。GetHashCode
另一种解决方案是IEquatable<T>
在类本身上实现并覆盖GetHashCode
,Distinct
然后Except
将遵循此实现:
public class Person : IEquatable<Person>
{
public string Name { get; set; }
public string BaseCode { get; set; }
public List<Location> Locations { get; set; }
public bool Equals(Person other)
{
if (other == null)
return false;
bool samePerson = Name == other.Name;
// This is simpler because of IEquatable<Location>
bool sameLocations = !Locations.Except(other.Locations).Any();
return samePerson && sameLocations;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
public class Location : IEquatable<Location>
{
public string Name { get; set; }
public bool Equals(Location other)
{
if (other == null)
return false;
return Name == other.Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
这导致更简单的调用:
var distinctPersons = persons.Distinct().ToList();