Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get difference between two array without using linq or Set operator using csharp ?

Status
Not open for further replies.

ahmedsa2018

Programmer
Apr 25, 2018
67
EG
I work on csharp
I have two arrays of string

A1 = [Watermelon, Apple, Mango, Guava, Banana]
A2 = [Orange, Kiwi, Apple, Watermelon]

i need to write code by csharp get difference between two arrays
and display difference between two arrays but without using linq or set operator

expected result
Mango
Guava
Orange
Kiwi
 
yes
correct
sorry for missed Banana

expected result will be

expected result
Mango
Guava
Banana
Orange
Kiwi

 
i tried and reached to result by linq

var array1 = new[] { "Watermelon", "Apple", "Mango", "Guava", "Banana" };
var array2 = new[] { "Orange", "Kiwi", "Apple", "Watermelon" };

var result = array2.Except(array1).Concat(array1.Except(array2));

but i need it to get result without using linq or set operator
 
Simply something like this should work:
iterate over first array and check every element if it is in the second array too - and if not then this is the different element.
Then do the same with the second array.
 
I tried what I described before:

Code:
using System;

class Program
{
	public static void Main(string[] args)
	{
		string[] a = {"Watermelon", "Apple", "Mango", "Guava", "Banana"};
		string[] b = {"Orange", "Kiwi", "Apple", "Watermelon"};

		Console.WriteLine("Differences:\n");	
		int numDiff = arrayDifference(a, b);
		string diffResult = numDiff == 0 ? "There are no differences" : "Number of differences found: " + numDiff;
		Console.WriteLine("\n" + diffResult + "\n");
		
		Console.Write("Press any key to continue . . . ");
		Console.ReadKey(true);
	}
	
	static int arrayDifference(string[] x, string[] y) {
		int numberOfDifferentElements = 0;
		
		foreach(string s in x) {
			if (Array.IndexOf(y, s) == -1) {
				Console.WriteLine(s);
				numberOfDifferentElements++;
			}
		}
		
		foreach(string s in y) {
			if (Array.IndexOf(x, s) == -1) {
				Console.WriteLine(s);
				numberOfDifferentElements++;
			}
		}
		
		return numberOfDifferentElements;
	}
}

Output:
Code:
Differences:

Mango
Guava
Banana
Orange
Kiwi

Number of differences found: 5

Press any key to continue . . .
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top