您正在尋找帶有第二個參數IEqualityComparer的重載函數。因此,讓你的比較器(例如:http://www.blackwasp.co.uk/IEqualityComparer.aspx),並在相交/除外使用相同的比較器。
對於泛型部分:也許你應該有一個模板的通用接口,例如描述該類具有字符串ID屬性的ObjectWithID。或者簡單地在你的比較器中使用動態(但我認爲這是非常非常反模式的,因爲如果使用不好的類型可能會產生運行時錯誤)。
您還有一個問題:將兩個不同類型的集合相交將導致Object(公共父類)的集合。然後你必須施放很多(反模式)。我建議你爲你的模板類創建一個通用的抽象類/接口,並且它正在工作。如果你需要轉換的元素回來,不要投,但使用visitior模式: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 . . .
我只獲得ID字段(不是全部)匹配和不匹配 我需要所有的屬性。任何幫助! – 2013-05-11 13:06:58
如果你想比較所有的屬性,那麼你將需要實現'IEqualityComparer' –
Ric
2013-05-11 13:13:28
我不想比較所有屬性。只需比較一個屬性(ID)並獲取另一個列表中的所有屬性 – 2013-05-11 13:17:20