Comparing values in 2 arrays? problem...

# Thread: Comparing values in 2 arrays? problem...

1. Member
Join Date
Dec 1969
Posts
38

## Comparing values in 2 arrays? problem...

Finding similarities/differences between 2 arrays <BR>OK, <BR>maybe it was the wine/beer last night, but my tiny little brain can&#039;t seem to figure this out. <BR>I have 2 arrays and I know for certain that both arrays have fields that contain the same value, but want to find the values in the second array that are NOT in the first array <BR>For example: <BR><BR>FirstArray[0].Value = &#039;dog&#039; <BR>FirstArray[1].Value = &#039;cat&#039; <BR><BR>SecondArray[0].Value = &#039;dog&#039; <BR>SecondArray[0].Value = &#039;cat&#039; <BR>SecondArray[0].Value = &#039;bird&#039; <BR>SecondArray[0].Value = &#039;cow&#039; <BR><BR>What I want to be able to do is somehow loop through the values of each and pick out <BR>&#039;bird&#039; and &#039;cow&#039;, as those are the values in which the FirstArray is missing. <BR>Make sense? <BR>Any help with this would be greatly appreciated! <BR><BR>Doug <BR>

2. mmm
Junior Member
Join Date
Dec 1969
Posts
15

## RE: Comparing values in 2 arrays? problem...

You can do it like this:<BR><BR>Dim firstArray() As String = {"cat", "dog"}<BR>Dim secondArray() As String = {"cat", "dog", "bird", "cow"}<BR>Dim missing As New ArrayList<BR>Dim i, j As Integer<BR>Dim isMissing As Boolean<BR>For i = 0 To secondArray.GetUpperBound(0)<BR>&nbsp;&nbsp;isMiss ing = True<BR>&nbsp;&nbsp;For j = 0 To firstArray.GetUpperBound(0)<BR>&nbsp;&nbsp;&nbsp;& nbsp;If (firstArray(j).Equals(secondArray(i))) Then<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;isMiss ing = False<BR>&nbsp;&nbsp;&nbsp;&nbsp;End If<BR>&nbsp;&nbsp;Next<BR>&nbsp;&nbsp;If (isMissing) Then<BR>&nbsp;&nbsp;&nbsp;&nbsp;missing.Add(second Array(i))<BR>&nbsp;&nbsp;End If<BR>Next<BR><BR>The ArrayList missing will contain "bird" and "cow"<BR><BR>There&#039;s probably a better way to do it, and I&#039;m sure someone else will post it... :-)<BR><BR>HTH,<BR><BR>mmm<BR>

3. Member
Join Date
Dec 1969
Posts
38

## RE: Comparing values in 2 arrays? problem...

worked great, thanks!<BR><BR>I found another way to do it if anyone&#039;s interested (must be an ArrayList though), I would be curious as to which is the most &#039;efficitient&#039; way....<BR><BR>...StringBuilder sb;<BR><BR>foreach(object item in Array1)<BR> {<BR> flag = array2.LastIndexOf(item.ToString());); <BR> if (flag == -1)<BR> {<BR> sb.Append(item.ToString());<BR> }<BR> }<BR><BR>Thanks!<BR>

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•