如何在 C# 中比较这些对象的一个或多个属性上的两个对象列表

本文关键字:对象 属性 列表 两个 一个 比较 | 更新日期: 2023-09-27 18:31:55

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

如何在 C# 中比较这些对象的一个或多个属性上的两个对象列表

你可以使你的类继承自 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;
       }
   }

您可以在此处找到此解决方案的详细信息

在这种情况下,最简单和最 OOP 的方法 imo 可能是一个简单的实现两种类型的 IComparable 接口,只需调用 CompareTo .

希望这有帮助。

例如覆盖

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));
}

然后调用列表的"等于"