i'm trying to compare lists,
i want to know if a values in a list exists more then 1 time in that list.
i have an arraylist of coordinates, and i want to get to know if there are points that are in the list, multiple times.
could you help me
i'm trying to compare lists,
i want to know if a values in a list exists more then 1 time in that list.
i have an arraylist of coordinates, and i want to get to know if there are points that are in the list, multiple times.
could you help me
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Nov 8, 2007, 10:12 AM
This problem is easier to solve if we first sort the ArrayList (or a copy thereof) so that any duplicated points are adjacent to each other. As the System.Drawing.Point struct doesn't implement IComparable, we need to create a custom IComparer class to do this.
Below, I've coded a quick console app to illustrate this approach with some sample data which contains duplicates:
using System;
using System.Collections;
using System.Drawing;
class Test
{
static void Main()
{
ArrayList points = new ArrayList();
points.Add(new Point(10,20));
points.Add(new Point(20,40));
points.Add(new Point(10,20));
points.Add(new Point(30,50));
points.Add(new Point(10,40));
points.Add(new Point(10,20));
points.Add(new Point(30,40));
points.Add(new Point(30,50));
// clone the ArrayList so that we can sort it without affecting original
ArrayList points2 = (ArrayList)points.Clone();
points2.Sort(new PointComparer());
// now check for duplicates
bool anyDuplicates = false;
int count = 1;
for (int i = 1; i < points2.Count; i++)
{
if (points2[i].Equals(points2[i-1]))
{
count++;
if (!anyDuplicates) anyDuplicates = true;
if (i == points2.Count - 1)
{
Console.WriteLine("{0} occurred {1} times", points2[i], count);
}
}
else
{
if (count > 1)
{
Console.WriteLine("{0} occurred {1} times", points2[i-1], count);
count = 1;
}
}
}
if (!anyDuplicates)
Console.WriteLine("There are no duplicated points");
Console.ReadLine();
}
}
class PointComparer : IComparer
{
public int Compare (object o1, object o2)
{
Point p1 = (Point)o1;
Point p2 = (Point)o2;
if (p1.X < p2.X || (p1.X == p2.X && p1.Y < p2.Y))
return -1;
else if (p1 == p2)
return 0;
else
return 1;
}
}