Deleting items while looping through the list
Anonymous delegates are very powerful in C#, especially when you are dealing with generics that can take a predicate.
How do you delete an item from the list while looping the list? One way is to collect all the items that are to be removed into another temporary collection. Next loop thru the temporary collection to remove the items from main collection…yak…
Here is a simple way.
List
listStrings.Add(“tom”);
listStrings.Add(“adams”);
listStrings.Add(“jake”);
listStrings.Add(“alice”);
listStrings.Add(“john”);
//I want to remove the users that starts with “j”.
//Here is the magic…
listStrings.RemoveAll(
delegate(string strRemove)
{
//You can put any logic here
return strRemove.StartsWith(“j”);
}
);
//Now the resulting collection will not have “jake” and “john”…
That's it, pretty cool right?
0 Comments:
Post a Comment
<< Home