2012-04-23 85 views
3

首先,我必須說我不是一個經驗豐富的程序員。我查看了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 
+0

當「* some *屬性值的差異」被允許時,您如何知道兩個對象是「相同的」?是否有一個特殊的屬性決定了「相同性」,然後其他屬性可以不同? – dasblinkenlight 2012-04-23 11:05:36

+0

對於屬性匹配的每個比較,我在列表中輸入「1」,如果不匹配則輸入「0」。然後我做一個!list.contains(1)以獲得所有匹配結果爲0的結果。 – Willem 2012-04-24 11:48:03

回答

6

您可以從IComparable你的類繼承,並以此爲基礎進行性能比較,你要像下面這樣:

class Employee : IComparable 
    { 
     private string name; 
     public string Name 
     { 
      get { return name; } 
      set { name = value ; } 
     } 

     public Employee(string a_name) 
     { 
      name = a_name; 
     } 

     #region IComparable Members 
     public int CompareTo(object obj) 
     { 
     Employee temp = (Employee)obj; 
     if (this.name.Length < temp.name.Length) 
      return -1; 
     else return 0; 
     } 
    } 

你可以找到這個解決方案的細節here

+0

謝謝你的例子。 – Willem 2012-04-23 13:59:37

+0

@Wallaedes很高興幫助:) – GETah 2012-04-23 14:41:24

4

最簡單,最OOP在這種情況下,方法imo可能是一個簡單的實現 的IComparable Interface在你的兩種類型,並簡單地打電話CompareTo

希望這會有所幫助。

2

例如覆蓋

public Coordinates(string x, string y) 
{ 
    X = x; 
    Y = y; 
} 

public string X { get; private set; } 
public string Y { get; private set; } 

public override bool Equals(object obj) 
{ 
    if (!(obj is Coordinates)) 
    { 
     return false; 
    } 
    Coordinates coordinates = (Coordinates)obj; 
    return ((coordinates.X == this.X) && (coordinates.Y == this.Y)); 
} 

然後調用列表的 '平等'