Identify common items in multiple arraylists

  • Thread starter Thread starter Ayoa
  • Start date Start date
A

Ayoa

I am trying to identify items that are common to 2 or more arraylists

e.g.

a = {2,4,6,8}
b = {4,5, 6,7,8}
C = {0,4,8,16}

I would like to return the common items in a new arraylist i.e. {4,8}.
(Similar to a set intersection operation). Can i achieve this using c#?

thanks
 
I would use a Hashtable as an intermediate object:

public ArrayList Intersect(params ArrayList[] lists)
{
if (lists.Count == 0)
{
return new ArrayList();
}
if (lists.Count == 1)
{
return lists[0].Clone();
}
Hashtable intersection = new Hashtable();
foreach (object obj in lists[0])
{
intersection.Add(obj, obj);
}
for (int i = 1; i < lists.Count; i++)
{
ArrayList keysToRemove = new ArrayList();
foreach (DictionaryEntry de in intersection)
{
if (!lists.Contains(de.Value))
{
keysToRemove.Add(de.Key);
}
}
foreach (object key in keysToRemove)
{
intersection.Remove(key);
}
}
return new ArrayList(intersection.Values);
}

The list you get back won't be in any particular order. If you want
them in a particular order, you should change the return line to:

return new ArrayList(intersection.Values).Sort();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top