首先我必须声明我不是一个经验丰富的程序员。我在 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
最佳答案
你可以让你的类继承自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
关于c# - 在 C# 中,如何根据这些对象的一个或多个属性比较两个对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10279177/