Elements in one Array (or Collection) But not in another

I apologize again for bringing up perl in context of C# but...

In perl if I have two arrays and want to know what elements are in one but not the other I could do the following (assume @a & @b are already populated):

my %seen // lookup table (hash)
my @aonly //answer

//Build lookup table
@seen{@b} = ();
foreach $item (@a) {
   push (@aonly, $item) unless exists $seen{$item};
}

Another way that might make more sense:

%seen //Lookup table to test membership of B
@aonly //answer

//Build lookup table
foreach $item (@b) {$seen{$item} = 1}

//Find only elements in @a and not in @b
foreach $item (@a) {
   unless ($seen{$item}) {
      //It's not in %seen, so add to @aonly
      push(@aonly,$item);
   }
}

I know the answer must lie with hash tables or dictionaries or the like but can't quite figer it out.

--Richard


Answer this question

Elements in one Array (or Collection) But not in another

  • Jameslee20



    List<T> ItemsInOneListButNotTheOther<T>(List<T> oneList, List<T> otherList)
    {
        List<T> answerList = new List<T>();

        foreach (T value in oneList)
        {
            if (! otherList.Contains(value))
            {
                answerList.Add(value);
            }
        }

        return answerList;
    }

     


  • SPersels

    Hummm. I can't get that code to work. I have two collections, do I need to copy or convert them to a List for this to work
  • aLaMaT

    Just change the signature of the method to take two ICollection objects instead of two Lists.

     

    Mads



  • Elements in one Array (or Collection) But not in another