Reputation: 13
I'm trying to remove objects from a BindingList that is bound to a DataGridView by doing this...
private void RemoveItems(List<Payment> removeList)
{
for (int i = removeList.Count - 1; i >= 0; i--)
{
sortableBindingPaymentList.Remove(removeList[i]);
}
}
Trying to debug this myself i attempted the following, however remover always = -1 (meaning that no match was found) and I'm 110% sure that my list of Payment's in removeList contains a match in my sortableBindingList...
private void RemoveItems(List<Payment> removeList)
{
int remover;
for (int i = removeList.Count - 1; i >= 0; i--)
{
remover = sortableBindingPaymentList.IndexOf(removerList[i]);
sortableBindingPaymentList.RemoveAt(remover);
}
}
Any help is appreciated and thanks in advance!
Upvotes: 1
Views: 1984
Reputation: 44048
I'm not sure I would go the IEquatable
way.. depending on the ORM you're using that might bring you some trouble.
Do your entities have a primary key? you can try this instead:
private void RemoveItems(List<Payment> removeList)
{
removeList.ForEach(x => sortableBindingPaymentList.RemoveAll(s => s.Id == x.Id));
}
P.S: I strongly suggest you to start using LinQ for these kind of operations instead of for
loops.
Upvotes: 1
Reputation: 33408
if removeList doesn't contain the same references (same objects) as the ones in sortableBindingPaymentList then the method will return -1, which i assume happens in your case.
It states here: that the "Remove" method of a list:
"This method determines equality using the default equality comparer EqualityComparer.Default for T, the type of values in the list."
Payment class should implement IEquatable interface.
Eg:
public class Payment : IEquatable
{
public bool Equals(Payment paymentObj)
{
//is current instance equal to payment OBJ?
//if yes, then return true otherwise false
}
}
Now this call should work even if you have different instances of objects in list collections.
sortableBindingPaymentList.Remove(removeList[i]);
Please post complete post if you need further help.
Upvotes: 1