简体   繁体   中英

C# - Removing duplicated items from dropdownlist in .net 4.0

Issue encountered in .net framework 4.0

I have 2 dropdownlist currently with one for months selection and another for year selection.

Both of their datasource are a datatable from a SQL which returns rows with year and month as columns. I then use the datatextfield and datavaluefield to specify which column to be used. Example:

string sql = "select.... group by...";//the query

DataTable dtMonthYear = db.getDataTable(sql); //got the datatable

ddlMonth.DataSource = dtMonthYear;
ddlMonth.DataTextField = "Month";
ddlMonth.DataValueField = "Month";
ddlMonth.DataBind();

ddlYear.DataSource = dtMonthYear;
ddlMonth.DataTextField = "Year";
ddlMonth.DataValueField = "Year";
ddlYear.DataBind();

Because of that, the year will have duplicated items in it, and i wish to eliminate the duplicated items.

I'd found out that linq can do it but unfortunately my framework is until 4.0 only and can't use the datarowextension. Here's the link that i got: LINQ query on a DataTable

Anyone has other idea?

Thanks

You can use Linq-To-DataSet in .NET 4 (even in 3.5):

DataTable years = dtMonthYear.AsEnumerable()
                  .GroupBy(r => r.Field<int>("Year"))
                  .Select( g => g.OrderBy(r => r.Field<int>("Month")).First())
                  .CopyToDataTable();

Note that you need to add using System.Linq;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM