从.net中的下拉列表中删除重复项

时间:2011-08-08 11:28:49

标签: c# .net asp.net drop-down-menu

如何从asp.net中的dropdownlist中删除重复项目,确保下拉列表中仅列出唯一值

很抱歉,如果这是重复的问题。搜索了SO但找不到它。

更新代码:

 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();
        }
}

由于

4 个答案:

答案 0 :(得分:2)

如果您的数据源使用通用列表,您可以使用LINQ清除任何重复项,然后再将其绑定到下拉控件 - 我假设您使用的是webforms吗?

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

这是我用来使用VehicleID删除我网站上的重复车辆对象,但这同样适用于您的下拉列表。

希望有所帮助

Truegilly

答案 1 :(得分:2)

我同意Pranay的回答,但在极少数情况下你无法使用查询访问db / sproc,这里是一个基于c#的方法:

    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();

答案 2 :(得分:2)

尝试DataView.ToTable Method (Boolean, String[])

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

答案 3 :(得分:1)

使用linq。这是一个例子

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));