您正在寻找带有第二个参数 IEqualityComparer 的重载函数。所以制作你的比较器(例如: http: //www.blackwasp.co.uk/IEqualityComparer.aspx),并在 intersect / except 中使用相同的比较器。
对于通用部分:也许你应该有一个通用的模板接口,例如 ObjectWithID 描述类有一个字符串 ID 属性。或者只是在你的比较器中使用动态(但我认为这是非常非常反模式,因为如果使用错误的类型,你可能会遇到运行时错误)。
您还有一个问题:将具有两种不同类型的两个集合相交将导致 Object (公共父类)的集合。然后你必须投很多(反模式)。我建议你为你的模板类创建一个通用的抽象类/接口,它正在工作。如果您需要将元素转换回来,请不要转换,而是使用访问者模式:http ://en.wikipedia.org/wiki/Visitor_pattern
示例(好):
static void Main(string[] args)
{
// http://stackoverflow.com/questions/16496998/how-to-copy-a-list-to-another-list-with-comparsion-in-c-sharp
List<Template> listForTemplate = new Template[] {
new Template(){ID = "1"},
new Template(){ID = "2"},
new Template(){ID = "3"},
new Template(){ID = "4"},
new Template(){ID = "5"},
new Template(){ID = "6"},
}.ToList();
List<Template1> listForTemplate1 = new Template1[] {
new Template1(){ID = "1"},
new Template1(){ID = "3"},
new Template1(){ID = "5"}
}.ToList();
var comp = new ObjectWithIDComparer();
var matches = listForTemplate.Intersect(listForTemplate1, comp);
var ummatches = listForTemplate.Except(listForTemplate1, comp);
Console.WriteLine("Matches:");
foreach (var item in matches) // note that item is instance of ObjectWithID
{
Console.WriteLine("{0}", item.ID);
}
Console.WriteLine();
Console.WriteLine("Ummatches:");
foreach (var item in ummatches) // note that item is instance of ObjectWithID
{
Console.WriteLine("{0}", item.ID);
}
Console.WriteLine();
}
}
public class ObjectWithIDComparer : IEqualityComparer<ObjectWithID>
{
public bool Equals(ObjectWithID x, ObjectWithID y)
{
return x.ID == y.ID;
}
public int GetHashCode(ObjectWithID obj)
{
return obj.ID.GetHashCode();
}
}
public interface ObjectWithID {
string ID { get; set; }
}
public class Template : ObjectWithID
{
public string ID { get; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Place { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class Template1 : ObjectWithID
{
public string ID { get; set; }
}
输出:
Matches:
1
3
5
Ummatches:
2
4
6
Press any key to continue . . .