Reputation: 5480
I am trying to remove an object from a list but it doesn't seem to be working.
In this scenario, I have an object called shape
and a collection of objects called shapes
.
I try to construct a new List<Shape> shapesInSameColumn
by:
List<Shape> shapesInSameColumn = new List<Shape>();
foreach (var shape in shapes)
{
if (fallingShape.ColumnNumber == shape.ColumnNumber)
{
shapesInSameColumn.Add(shape);
}
}
What I want to do now, is remove just one object from the above collection. I do this by:
shapesInSameColumn.Remove(fallingShape);
fallingShape happens to be at index 1. But, when I perform the .Remove, it removes the object at index 0.
How can I fix this problem?
Upvotes: 1
Views: 921
Reputation: 12295
if (fallingShape.ColumnNumber == shape.ColumnNumber &&
!object.ReferenceEquals(fallingShape,shape))
{
shapesInSameColumn.Add(shape);
}
Instead of removing don't even add it to shapesInSameColumn
Here reference of fallingshape and shape is being compared. Now, there is a possibility that falling shape and shape both have same column number but different object. In that case add it else just not add it.
Upvotes: 4
Reputation: 63065
try below
shapesInSameColumn.RemoveAll(s => somecondition);
for example you need to remove shapes with ID equal to 1
shapesInSameColumn.RemoveAll(s => s.ID ==1);
Upvotes: 1