find if a collection contains another collection

Hello,

I have two collections of string and I want to know if the first one contains the second (which menas all the strings in the second are also in the first)

is there a build in function which does it if not what is the best way to do it (I'm sure sorting is involved)

Thanks.




Answer this question

find if a collection contains another collection

  • popit

    I think you would have to go through each element of each array and compare the values from one array with the current position in the other array.

    something like....

    foreach (string currentItem in firstArray)

    {

    foreach(string theSecondArrayCurrentItem in theSecondArray)

    {

    if (currentItem.Equals(theSecondArrayCurrentItem))

    {

    //handle it, the item exists in both collections

    }

    }

    }

    This will be very ineffecient and slow, since it has to go through each element of each array....can take its time depending on how many items you have in the array's!

    you maybe better using perhaps a hashtable, that is if your array contains some unique "key" to reference/match up with the element appropriately.

    The hashtable of course only allows 1 key to be added, with its value but I am guessing this is not what you maybe after

    This is again probably overkill, but just a thought to keep, you could add the collections into a DataSet, then filter the dataset to see if the item you want to check, exists in the other array collection, if it does, you will get a result back - this would mean that yes there is a duplicate on the requested value to check, again, probably overkill.



  • find if a collection contains another collection