Finding Duplicate Elements in Array [C# Code]


You might searched a lot on internet for finding duplicate elements in an array but not succeded with correct one. Here I am going to explain with code o=how you can determine if an array contains duplicate elements.It might helps you.

Here I have taken a fixed length array with hardcoded values.
You can use your own array which is being returned from another methods etc.
Creatd a Button,on click of button I am calling a method which returns true or false and Showing the same to the user through messagebox.
Do reply if you have some problem in running this code.



using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class Form1
{

static int[] numbers = {1,2,3,1,5};

private void Button1_Click(System.Object sender, System.EventArgs e)
{
bool duplicates = false;

duplicates = IsArrayDuplicated(numbers);

MessageBox.Show(duplicates.ToString());

}

private static bool IsArrayDuplicated(int[] numbers)
{

bool result = false;

int n = 0;

int n1 = 0;

int i = 0;

result = false;

//Dim bits As New BitArray(numbers.Length + 1)


for (n = i; n <= numbers.Length - 1; n++) {

for (n1 = i + 1; n1 <= numbers.Length - 1; n1++) {

if (numbers[n] == numbers[n1] & n != n1) {
result = true;

break;


} else {
continue;

}

}

}

return result;

}

}



Please rate this article if it is helpfull to you.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: