首先,我必須說我不是一個經驗豐富的程序員。我查看了StackOverflow中的類似問題,但似乎找不到適合我的技巧的解決方案。在C#中,我需要根據這些對象中的一個或多個屬性值來比較兩個對象列表。我想要創建兩個新列表,即左側存在的對象之一,但在右列表中有一些屬性值存在差異,或根本不存在,反之亦然。如何在C#中比較這些對象的一個或多個屬性上的兩個對象列表?
之前,我只需要比較兩個基於一個價值,所以我沒有在對象上,但上線工作,所以我做了這樣的事情:
(LeftItems and RightItems are Entities)
List<String> leftList = new List<string>();
List<String> rightList = new List<string>();
List<String> leftResultList = new List<string>();
List<String> rightResultList = new List<string>();
List<String> leftResultObjList = new List<string>();
List<String> rightResultObjList = new List<string>();
foreach (item i in leftItems)
{
leftlist.Add(i.value);
}
//same for right
foreach (string i in leftList)
{
if(!rightList.contains(i))
{
leftResultList.Add(i);
}
}
//same for the right list
現在我來比較多個值,所以我創建其中有幾個特性,我需要比較的一類,所以我喜歡做與上述相同,但對象屬性:
class CompItems
{
string _x;
string _y;
public CompItems(string x, string y)
{
_x = x;
_y = y;
}
}
foreach (item i in leftItems)
{
leftList.Add(new CompItem(i.value1,i.value2));
}
//same for the right list
foreach (CompItem c in leftItems)
{
// Here is where things go wrong
if(one property of object in rightItems equals property of object in leftItems) && some other comparisons
{
resultLeftObjList.Add(c)
}
}
//And the same for the right list
當「* some *屬性值的差異」被允許時,您如何知道兩個對象是「相同的」?是否有一個特殊的屬性決定了「相同性」,然後其他屬性可以不同? – dasblinkenlight 2012-04-23 11:05:36
對於屬性匹配的每個比較,我在列表中輸入「1」,如果不匹配則輸入「0」。然後我做一個!list.contains(1)以獲得所有匹配結果爲0的結果。 – Willem 2012-04-24 11:48:03