Labels

Friday, August 17, 2007

Tinker Collections Midway

Hi,

Can you tamper the collection in between of a for loop?

The solution is two fold:

· For loop: Allows

· ForEach: Does not allow.

ArrayList:

------------------------------------------------------------------------

ArrayList array = new ArrayList();

array.Add("AA");

array.Add("AB");

array.Add("AC");

array.Add("AD");

array.Add("AE");

MessageBox.Show(array.Count.ToString()); // 5

for (int i = 0; i < array.Count; i++)

{

if (array[i].Equals("AA"))

{

array.Remove(array[i]); // Note: No need to update the counter ‘i’

}

}

// For each will not allow to tamper the collection while looping

//foreach (string str in array)

//{

// if (str.Equals("AB"))

// {

// array.Remove(str);

// }

//}

MessageBox.Show(array.Count.ToString()); // 4

------------------------------------------------------------------------

HashTable:

------------------------------------------------------------------------

string strKey, strValue;

Hashtable hash = new Hashtable();

hash.Add("AA", "AAA");

hash.Add("AB", "AAB");

hash.Add("AC", "AAC");

hash.Add("AD", "AAD");

hash.Add("AE", "AAE");

MessageBox.Show(hash.Count.ToString());

string[] arrKeys = new string[hash.Count];

hash.Keys.CopyTo(arrKeys, 0);

for (int i = 0; i < arrKeys.Length; i++)

{

strKey = arrKeys[i];

if (strKey.Equals("AB"))

{

hash.Remove(strKey);

}

}

// For each will not allow to tamper the collection while looping

//foreach (string str in hash.Keys)

//{

// if (str.Equals("AB"))

// {

// hash.Remove(str);

// }

//}

MessageBox.Show(hash.Count.ToString());

------------------------------------------------------------------------

Mind it from next time……. J

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment