Remove duplicate items from dropdownlist in .net

13,641

Solution 1

if your datasource uses a generic list, you could use LINQ to clear any duplicates before you bind it to your dropdown control - im assuming your using webforms ?

        // ******
        // Remove Any Duplicate Vehicles
        // ********************
        List<Vehicle> NoDuplicatesVehicleList = ListVehicle.AllVehicles;
        NoDuplicatesVehicleList = NoDuplicatesVehicleList.GroupBy(x => x.VehicleID).Select(x => x.First()).ToList();

this is what i have used to remove duplicate vehicle objects on my site using the VehicleID, but the same would apply to your dropdown.

hope that helps

Truegilly

Solution 2

I agree w/ Pranay's answer, but in the somewhat rare case that you don't have access to the db/sproc with the query, here's a c# based approach:

    foreach (DataRow row in dt.Rows)
    {
        string itemName = Convert.ToString(row["colname"]);
        if (dt.Select(String.Format("Colname='{0}'", itemName)).Count() > 1)
            row.Delete();
    }
    dt.AcceptChanges();

Solution 3

Try DataView.ToTable Method (Boolean, String[])

DataTable newTable = oldTable.DefaultView.ToTable(true,"{your column name}");

Solution 4

Use linq. here is an example

using System.Collections;
using System.Linq;


ArrayList inputList = new ArrayList();
ArrayList outputList = new ArrayList();
inputList.Add(1);
inputList.Add(2);
inputList.Add(3);
inputList.Add(1);

inputList.ToArray().Distinct().ToList()
            .ForEach(a => outputList.Add(a));
Share:
13,641
xorpower
Author by

xorpower

Reached 500 Repo on May 22'11 Reached 600 Repo on Jul 29'11 Reached 700 Repo on Aug 10'11 Reached 800 Repo on Sep 09'11 Reached 900 Repo on Oct 13'11 Reached (&amp; crossed) 1000 Repo during Mar 14-19'12 Reached 1300 Repo on May 8 2013

Updated on June 30, 2022

Comments

  • xorpower
    xorpower almost 2 years

    How can one remove duplicate items from dropdownlist in asp.net making sure that only unique values are listed in dropdownlist

    Sorry if this is the duplicate question. Searched the SO but couldn't find it.

    UPDATED CODE:

     private void BindDropdown(DropDownList ddlColumn)
        {
            DataTable dtBinddropDown = new DataTable();
            DataSet dsBinddrodown = new DataSet("dsSample");
            dtBinddropDown = (DataTable)Session[GlobalConstants.SESSION_MYSESSION];
            dsBinddrodown.Tables.Add(dtBinddropDown.Copy());
            System.Collections.ArrayList arItems = new System.Collections.ArrayList();
    
            if (ddlColumn.ID == "ddlEntryDate")
            {
                for (int i = 1; i < dsBinddrodown.Tables[0].Rows.Count; i++)
                {
                    arItems.Add(dsBinddrodown.Tables[0].Rows[i]["Column 1"].ToString());
                }
                ddlColumn.DataSource = arItems;
                ddlColumn.DataBind();
            }
    }
    

    Thanks