I have an arraylist with few duplicate items. I need to know the count of each duplicated item. I am using 2.0 so cannot use linq.
I had posted a similar question earlier, but my question was not clear. Thanks Prady
I have an arraylist with few duplicate items. I need to know the count of each duplicated item. I am using 2.0 so cannot use linq.
I had posted a similar question earlier, but my question was not clear. Thanks Prady
I've done something in the past. My solution was to loop through the ArrayList and store the counts in a dictionary. Then loop though the dictionary to display the results:
ArrayList list = new ArrayList();
list.Add(1);
list.Add("test");
list.Add("test");
list.Add("test");
list.Add(2);
list.Add(3);
list.Add(2);
Dictionary<Object, int> itemCount = new Dictionary<object, int>();
foreach (object o in list)
{
if (itemCount.ContainsKey(o))
itemCount[o]++;
else
itemCount.Add(o, 1);
}
foreach (KeyValuePair<Object, int> item in itemCount)
{
if (item.Value > 1)
Console.WriteLine(item.Key + " count: " + item.Value);
}
Output:
test count: 3
2 count: 2
Edit Realized I used the var keyword which is not a 2.0 feature. Replaced it with KeyValuePair.
i needed something similar for a project a long time ago, and made a function for it
static Dictionary<object, int> GetDuplicates(ArrayList list, out ArrayList uniqueList)
{
uniqueList = new ArrayList();
Dictionary<object, int> dups = new Dictionary<object, int>();
foreach (object o in list)
{
if (uniqueList.Contains(o))
if (!dups.ContainsKey(o))
dups.Add(o, 2);
else
dups[o]++;
else
uniqueList.Add(o);
}
return dups;
}