Home > Software engineering >  How can I figure out if one List has different value than the other List
How can I figure out if one List has different value than the other List

Time:07-30

I have two special List(defaultGeometry,changedGeometry) and I have one another method (AreCoordinatesEqual) which can compare coordinates and return boolean.

for (int i = 0; i < defaultGeometry.Count; i  )
{
    for (int j = 0; j < changedGeometry.Count; j  )
    {
        if (!AreCoordinatesEqual(defaultGeometry[i], changedGeometry[i]))
        {
            return false;
        }
     }
}

My question is; If, changedGeometry has even one different coordinate(or lets say value) from defaultGeometry then I should return false. Basically I want to match every changedGeometry coordinates with every defaultGeometry coordinates so that I will realize If any foreign value changedGeometry has. Please note that; defaultGeometry can have different values it's ok. So I tried some contain methods but I would like to use my method(AreCoordinatesEqual) in that case and nested loops looks the best solution. But any other ways are appreciated. I would be grateful for any help at this point. Thank you

CodePudding user response:

Linq appraoch with Zip() and All()

return defaultGeometry.Zip(changedGeometry,(d,c) => AreCoordinatesEqual(d,c)).All(x => x);

... or you just remove the second for loop in your own appraoch and add return true; at the end

CodePudding user response:

I think 5th row's changedGeometry number is wrong

for (int i = 0; i < defaultGeometry.Count; i  )
{
    for (int j = 0; j < changedGeometry.Count; j  )
    {
        if (!AreCoordinatesEqual(defaultGeometry[i], changedGeometry[**j**]))
        {
            return false;
        }
     }
}

CodePudding user response:

I would recommand to just use the .Except() method from LINQ. The only condition is to make sure your entity implements the IEqualityComparer interface

Here is a sample and its result with Points (which act as your coordinates):

using System.Drawing;

var oldPoints = new List<Point>()
{
    new Point(0, 0),
    new Point(1,1),
    new Point(2,2),
    new Point(3,3),
    new Point(4,4),
};
var newPoints = new List<Point>()
{
    new Point(0, 0),
    new Point(1,1),
    new Point(-2,-2),
    new Point(-3,-3),
    new Point(-4,-4),
};

var changedPoints = newPoints.Except(oldPoints);

var changedPointsCount = changedPoints.Count();
Console.WriteLine($"Number of point changed: {changedPointsCount}");
if(changedPointsCount > 0)
{
    foreach(var changedPoint in changedPoints)
    {
        Console.WriteLine($"New point detected: X={changedPoint.X} # Y={changedPoint.Y}");
    }
}

Output:

Number of point changed: 3
New point detected: X=-2 # Y=-2
New point detected: X=-3 # Y=-3
New point detected: X=-4 # Y=-4
  • Related