Find The Common Elements In Two Arrays In C#
Code snippet for how to Find The Common Elements In Two Arrays In C# with sample and detail explanation
Working with arrays is a fundamental part of any programming language. In this article, we will navigate through a simple program in C# language that finds the common elements in two different arrays.
Code snippet for Finding Common Elements in Two Arrays
Below you’ll find a simple program that compares two preset arrays and outputs any elements that are in both arrays:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {1,2, 8, 9, 10};
var commonElements = array1.Intersect(array2);
foreach (var element in commonElements)
{
Console.WriteLine(element);
}
}
}
Code Explanation for Finding Common Elements in Two Arrays
We’ll now walk through this code step by step to understand what exactly is happening.
Firstly, the program starts by declaring two arrays - array1
and array2
.
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {1,2, 8, 9, 10};
Afterward, we use the .Intersect()
function, which is a built-in function from the LINQ (Language Integrated Query) framework. This function returns a new collection (in this case it’s an IEnumerable
) that includes the common elements found in both arrays.
var commonElements = array1.Intersect(array2);
Lastly, we use a foreach
loop to loop through our new IEnumerable
collection. For every common element found in both array1
and array2
, the program will output the element to the console.
foreach (var element in commonElements)
{
Console.WriteLine(element);
}
The benefit of this simple implementation is that it offers a quick, efficient way to find common elements, without needing to manually compare every element in both arrays. The Intersect
function does this by using a set comparison, essentially viewing each array as a set of unique elements.
Keep in mind that this method returns only the common elements present in both arrays and it does not return duplicate elements. In other words, if an element is present multiple times in both arrays, it will only be returned once.
In conclusion, by using built-in functions and well-structured loops, we can easily manipulate arrays to find common elements in C#.