【发布时间】:2012-04-23 10:54:24
【问题描述】:
首先我必须说我不是一个经验丰富的程序员。我在 StackOverflow 上查看了类似的问题,但似乎没有找到一个合适的答案,我可以用我有限的技能来实现。
在 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
【问题讨论】:
-
当“一些属性值的差异”被允许时,你怎么知道两个对象是“相同的”?是否有一个特殊的属性决定“相同”,然后其他属性可以不同?
-
对于属性匹配的每个比较,我在列表中放置一个“1”,如果没有匹配,则放置一个“0”。然后我执行一个 !list.contains(1) 来获得所有匹配项都为 0 的结果。
标签: c# list object properties compare