Here we are going to find out the distinct elements from an array using:
- For Loop
- LINQ
In order to execute the code I’ve created a simple console application to print out the result.
Please find complete code below:
- Using For loop
using System; using System.Collections.Generic; using System.Linq; namespace PracticeConsole { class Program { static void Main(string[] args) { int[] items = { 2, 3, 5, 3, 7, 5 }; int n = items.Length; Console.WriteLine("Unique array elements: "); for (int i = 0; i < n; i++) { bool isDuplicate = false; for (int j = 0; j < i; j++) { if (items[i] == items[j]) { isDuplicate = true; break; } } if (!isDuplicate) { Console.WriteLine(items[i]); } } Console.ReadLine(); } } }
Result:
2. Using LINQ
using System; using System.Collections.Generic; using System.Linq; namespace PracticeConsole { class Program { static void Main(string[] args) { int[] items = { 2, 3, 5, 3, 7, 5 }; IEnumerable<int> uniqueItems = items.Distinct<int>(); Console.WriteLine("Unique array items: " + string.Join(", ", uniqueItems)); Console.ReadLine(); } } }
Result: