首先,我必须说我不是一个经验丰富的程序员。我查看了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