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());
}
}
}
}
Quick Notes for easy understanding. Chapters are on C#.Net,Linq,OOPS,Design Patterns,UML,Tools for development, Databases and many others. - Sid
Friday, June 17, 2011
Subscribe to:
Post Comments (Atom)
Code Formater
Paste Here Your Source Code | ||||||||||||||
Source Code Formatting Options | ||||||||||||||
|
||||||||||||||
Copy Formatted Source Code | ||||||||||||||
Preview Of Formatted Code |
No comments:
Post a Comment