如何从两个全部实现IComparable的对象列表中找到相交的对象?
public List<T> Intersect<T>(List<T> list1, List<T> list2) where T : IComparable<T> {
return ... ;
}
答案 0 :(得分:1)
像这样的东西
public List<T> Intersetc<T>(List<T> list1, List<T> list2) where T : IComparable<T>
{
return list1.Intersect(list2, new MyEqualityComparer<T>()).ToList();
}
public class MyEqualityComparer<T> : IEqualityComparer<T> where T : IComparable<T>
{
public bool Equals(T t1, T t2)
{
return t1.CompareTo(t2) == 0;
}
public int GetHashCode(T t)
{
return 0;
}
}
答案 1 :(得分:1)
为什么不简单:
public List<T> Intersect<T>(List<T> list1, List<T> list2) where T : IComparable<T>
{
var intersect = list1.Intersect(list2);
return intersect.ToList();
}