Jakka .NET

I am Suresh Jakka, software architect at GeoCue Corp, Madison, Alabama. I have been reading serveral tech blogs and learning a lot. It is about time for me to start a blog on .NET in general so that others can learn from my experiences. Here I will be blogging about obstacles that I encounter in my day-to-day programming world and about the solutions I found.

Saturday, February 27, 2010

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 <strings> listStrings = new listStrings();
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?