Friday, June 17, 2011

How to remove item from a List in a Loop ?

It is not an easy task of removing an item from the list in the loop. By just doing the loop and removing the item we can encounter much complications.

So better way is to loop the list from bottom -> up and remove the item based on the condition.

Sample code piece -



using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> ls = new List<string>();

            ls.Add("a");
            ls.Add("b");
            ls.Add("c");
            ls.Add("d");
            ls.Add("e");

            for (int i = ls.Count - 1; i >= 0; i--)
            {


                if (ls[i] == "d")
                {
                    Console.WriteLine("del:" + ls[i].ToString());
                    ls.RemoveAt(i);
                }

            }

            for (int i = 0; i < ls.Count; i++)
            {
                Console.WriteLine(ls[i].ToString());
            }

        }
    }
}

No comments:

Post a Comment

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code