c# - How to delete duplicate elements from an array

Array delete duplicate elements
The following asp.net c# example code demonstrate us how can we remove/delete duplicate elements from an array programmatically at run time in an asp.net application. .Net framework's Enumerable.Distinct() method returns distinct elements from a sequence by using the default equality comparer to compare values.

So, we can create an elements collection by calling Enumerable.Distinct() method for specified array object. We can call this method as Array.Distinct(). The ToArray() method convert the collection to an array object.

Next, we need to resize the instance array object as the same size of distinct array. At last, we loop through the distinct array object and populate instance array elements with value from distinct array elements. Finally, the process removed/deleted duplicate elements from a specified array object.

<%@ Page Language="C#" AutoEventWireup="true"%>  
<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
        string[] colors = new string[]

        Label1.Text = "colors array.........<br />";
        foreach (string s in colors)
            Label1.Text += s + "<br />";

        var distinctcolors = colors.Distinct().ToArray();
        Array.Resize(ref colors, distinctcolors.Length);

        for (int i = 0; i < colors.Length; i++)
            colors[i] = distinctcolors[i];

        Label1.Text += "<br />distinct colors array.........<br />";
        foreach (string s in colors)
            Label1.Text += s + "<br />";
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array delete duplicate elements</title>  
    <form id="form1" runat="server">  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array delete duplicate elements
        <hr width="550" align="left" color="LightBlue" />    
        <br />
            Text="delete duplicate elements from array"  
More c# examples