'Remove duplicates from List only if last 2 elements are same
I have a method :
public List<Point> RemoveDuplicatePoints(List<Point> theVertices)
{
var aVertices = new List<Point>();
foreach (Point aPoint in theVertices)
{
if ((int)theVertices.Last().X == (int)aPoint.X && (int)theVertices.Last().Y == (int)aPoint.Y)
{
continue;
}
aVertices.Add(aPoint);
}
aVertices.Add(new Point(theVertices.Last().X, theVertices.Last().Y));
return aVertices;
}
I want to remove duplicate from the list only if the last point is equal to previous point which is achieved from above RemoveDuplicatePoints(List theVertices) method.
Results :
a)Input list:
List<Point> aLocalList = new List<Point>(); aLocalList.Add(new Point(387.238493723849, 645.502092050209)); aLocalList.Add(new Point(386.610878661088, 658.682008368201)); aLocalList.Add(new Point(148.744769874477, 951.150627615063)); aLocalList.Add(new Point(380.962343096234, 846.338912133891)); aLocalList.Add(new Point(478.870292887029, 741.52719665272)); aLocalList.Add(new Point(483.26359832636, 705.753138075314)); aLocalList.Add(new Point(483.26359832636, 705.753138075314));
b)Output list has these points: this.RemoveDuplicatePoints(aLocalList);
//Expected result achieved
Point(387.238493723849, 645.502092050209);
Point(386.610878661088, 658.682008368201);
Point(148.744769874477, 951.150627615063);
Point(380.962343096234, 846.338912133891);
Point(478.870292887029, 741.52719665272);
Point(483.26359832636, 705.753138075314);
2) a)Input list:
List<Point> aLocalList1 = new List<Point>();
aLocalList.Add(new Point(387.238493723849, 645.502092050209));
aLocalList.Add(new Point(386.610878661088, 658.682008368201));
aLocalList.Add(new Point(148.744769874477, 951.150627615063));
aLocalList.Add(new Point(380.962343096234, 846.338912133891));
aLocalList.Add(new Point(478.870292887029, 741.52719665272));
aLocalList.Add(new Point(483.26359832636, 705.753138075314));
aLocalList.Add(new Point(148.744769874477, 951.150627615063));
b) Output List has these points : this.RemoveDuplicatePoints(aLocalList1);
Point(387.238493723849, 645.502092050209);
Point(386.610878661088, 658.682008368201);
Point(380.962343096234, 846.338912133891);
//Point(148.744769874477, 951.150627615063); is missing but its added at the end which is right
Point(478.870292887029, 741.52719665272);
Point(483.26359832636, 705.753138075314);
Point(148.744769874477, 951.150627615063);
I want to remove the duplicate Point only if last two are same. If comparison happens between any other element in list except last() , the list element has to be retained. How to achieve this ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
