c# - How to get distinct values from an array

Array distinct
The following asp.net c# example code demonstrate us how can we distinct an array pogrammatically at run time in an asp.net application. .Net framework's Enumerable.Distinct() method allow us to get distinct elements from a sequence by using the default equality comparer to compare values. Distinct() method exists in System.Linq namespace.

We can call this method as this way Array.Distinct(). We also can convert the Distinct() method returned elements collection to an array object by using ToArray() method. We need to create a new array object to hold the array distinct values.
array-distinct.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  
  
<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Chestnut Munia",
            "Java Sparrow",
            "Western Bluebill",
            "Chestnut Munia",
            "Water Pipit",
            "Water Pipit"
        };

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

        string[] distinctbirds = birds.Distinct().ToArray();

        Label1.Text += "<br />distinct birds array.........<br />";
        foreach (string s in distinctbirds)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array distinct</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array distinct
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
  
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="X-Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array distinct"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>
More c# examples