Alex Rivera | Logout

Check two List<int>'s for the same numbers

Asked 2009-01-26T14:55:02.670
24

I have two List's which I want to check for corresponding numbers.

for example

List<int> a = new List<int>(){1, 2, 3, 4, 5};
List<int> b = new List<int>() {0, 4, 8, 12};

Should give the result 4. Is there an easy way to do this without too much looping through the lists?

I'm on 3.0 for the project where I need this so no Linq.

Edit
Report

2 Answers

0

Here is a method that removed duplicate strings. Change this to accomidate int and it will work fine.

public List<string> removeDuplicates(List<string> inputList)
    {
        Dictionary<string, int> uniqueStore = new Dictionary<string, int>();
        List<string> finalList = new List<string>();

        foreach (string currValue in inputList)
        {
            if (!uniqueStore.ContainsKey(currValue))
            {
                uniqueStore.Add(currValue, 0);
                finalList.Add(currValue);
            }
        }
        return finalList;

    }

Update: Sorry, I am actually combining the lists and then removing duplicates. I am passing the combined list to this method. Not exactly what you are looking for.

answered 2009-01-26T15:15:29.057
0

Wow. The answers thus far look very complicated. Why not just use :

List<int> a = new List<int>() { 1, 2, 3, 4, 5, 12, 13 };
List<int> b = new List<int>() { 0, 4, 8, 12 };

...

public List<int> Dups(List<int> a, List<int> b)
{
    List<int> ret = new List<int>();

    foreach (int x in b)
    { 
        if (a.Contains(x))
        {
           ret.add(x);
        }
    }

    return ret;
}

This seems much more straight-forward to me... unless I've missed part of the question. Which is entirely possible.

answered 2009-01-26T16:05:27.927

Your Answer