How to compare in C # two lists of objects by one or several properties of these objects?

First of all, I have to say that I am not an experienced programmer. I looked at similar issues in StackOverflow, but didn't seem to find a suitable answer that I could implement with my limited skills.

In C #, I need to compare two lists of objects based on the values ​​of one or more properties in these objects. I want to create two new lists, one of the objects that exist on the left, but have differences in some property values ​​inside or do not exist at all in the right list and vice versa.

Before I had to compare only two values ​​based on a single value, I did not have to work with objects, but on a line, so I did something like this:

(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
+3
3

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

+6

, imo, IComparable Interface , CompareTo.

, .

+4

For example, override

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

And then call "Equal" from the list

+2
source

All Articles