Link to home
Start Free TrialLog in
Avatar of Kai77
Kai77

asked on

Removing elements from arraylist

I have a arraylist arrHighlightIDs which for instance can be something like (67,67,68,68,68,100,101,101)

I want too remove all the elements with the same value (e.g. 68, his variable is randomly generated) so I wrote the following code:

iNumberOfTimes = 0;
foreach(object item in arrHighlightIDs)
{
      if (item.ToString() == arrHighlightIDs[iRandValue])
      {
            iNumberOfTimes = iNumberOfTimes + 1;
      }
}      
Response.Write("Number of times to be deleted: " + iNumberOfTimes);
                              
while (iNumberOfTimes > 0)
{
      arrHighlightIDs.Remove(arrHighlightIDs[iRandValue]);
      iNumberOfTimes = iNumberOfTimes - 1;
}


First of all this does not work, second of all, there must be an easier way to delete multiple elements with the same value from an arraylist at once. Any ideas?

Thanks
Avatar of Fahad Mukhtar
Fahad Mukhtar
Flag of Pakistan image

//arrHighlightIDsis the actual source list
//arrHighlightIDs2 is another that i have created that is used to contain non-redundant data

ArrayList arrHighlightIDs2  = new ArrayList();

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

{
if (arrHighlightIDs2.Contains(Convert.ToDouble(arrHighlightIDs[i]))==false)
    {                    
    arrHighlightIDs2.Add((Convert.ToDouble(arrHighlightIDs[i])));                              
    }                    
}
arrHighlightIDs= arrHighlightIDs2;
Avatar of Kai77
Kai77

ASKER

Sorry, arrHighlightsIDs is a stringcollection (instead of an arraylist).  


So the following error occurs:
Cannot implicitly convert type 'System.Collections.ArrayList' to 'System.Collections.Specialized.StringCollection'

Anyway to convert the arrHighlightIDs2 into a stringcollection?
try this

System.Collections.Specialized.StringCollection arrHighlightIDs2  = new System.Collections.Specialized.StringCollection ();

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

{
if (arrHighlightIDs2.Contains(Convert.ToString(arrHighlightIDs[i]))==false)
    {                    
   arrHighlightIDs2.Add((Convert.ToString(arrHighlightIDs[i])));                              
   }                    
}
arrHighlightIDs= arrHighlightIDs2;
ASKER CERTIFIED SOLUTION
Avatar of Fahad Mukhtar
Fahad Mukhtar
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial