On 2007-11-27 14:24:59 -0800, "DNB" <ii@ii.comsaid:
>
I am using generic in the following example.
But I can figure out how to remove an item in the collection??
You'll need to use one of the methods with the word "Remove" in the name.
Your person class doesn't implement IEquatable or override
Object.Equals(), so the only way as the class is now to use Remove() is
if you retain the reference to the object you added, for later use in
removal.
Alternatives include RemoveAll() and RemoveAt(). With the former, you
could use an anonymous method as your predicate:
myPerson.RemoveAll(delegate (Person person)
{ return person.Name == "2 Test"; });
As the name of the method implies, that would remove all instances
matching your criteria. If you only want to remove the first instance
or you know for sure there is only ever one instance, you could search
the list manually:
for (int iperson = 0; iperson < myPerson.Count; iperson++)
{
if (myPerson[iperson].Name == "2 Test")
{
myPerson.RemoveAt(iperson);
break;
}
}
On average that would cut the operation time in half. RemoveAll() will
always enumerate the whole list, so in situations where you can stop at
the first element you find, on average you'd only have to enumerate
half the list instead of all of it.
Of course, you could always implement IEquatable or override
Object.Equals() in your Person class, if appropriate. Then the
Remove() method could be used directly, by creating a new instance of
Person that would test as equal to the one you want to remove and
passing that instance to Remove().
Pete