2012-04-23 79 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)); 
} 

然后调用列表的 '平等'