Remove Duplicates from Array - CSharp System

CSharp examples for System:Array Operation

Description

Remove Duplicates from Array

Demo Code


using System.Collections.Generic;
using System;/*from  w  ww  . jav a 2  s  .c  om*/

public class Main{
        public static T[] RemoveDuplicates<T>(T[] array) where T: IComparable<T>
        {
            if (array.Length <= 1)
            {
                return array;
            }

            int i = 1;
            int offset = 0;
            while (i < array.Length)
            {
                if (array[i].Equals(array[i - 1]))
                {
                    offset++;
                }
                else
                {
                    array[i - offset] = array[i];
                }
                i++;
            }

            T[] copyArray = new T[array.Length - offset];
            Array.Copy(array, copyArray, array.Length - offset);
            return copyArray;
        }
}

Related Tutorials