我正在尝试优化SharePoint webpart的代码。我有一个转发器控件:
<asp:Repeater ID="CountryOptionsRepeater" runat="server">
<ItemTemplate>
<option value='<%#Eval("CountryName") %>'><%#Eval("CountryName") %></option>
</ItemTemplate>
</asp:Repeater>
我用数据表填充它
countriesList = countriesList.Distinct<String>().ToList<String>();
countriesList.Sort();
//var noDupsCountriesList = new HashSet<String>(countriesList);
DataTable dt = new DataTable();
dt.Columns.Add("CountryName");
foreach (String countryName in countriesList)
{
DataRow dr = dt.NewRow();
dr["CountryName"] = countryName;
dt.Rows.Add(dr);
}
CountryOptionsRepeater.DataSource = dt;
CountryOptionsRepeater.DataBind();
this.DataBind();
有没有办法将HashSet对象(noDupsCountriesList)直接绑定到具有相同配置的转发器的DataSource,以实现优化?
类似的东西:
//countriesList = countriesList.Distinct<String>().ToList<String>();
//countriesList.Sort();
var noDupsCountriesList = new HashSet<String>(countriesList);
CountryOptionsRepeater.DataMember = "CountryName"; // ??
CountryOptionsRepeater.DataSource = noDupsCountriesList;
CountryOptionsRepeater.DataBind();
this.DataBind();
答案 0 :(得分:6)
我认为这一行可以取代你的第二段代码:
CountryOptionsRepeater.DataSource =
countriesList
.Distinct()
.OrderBy(c => c)
.Select(c => new { CountryName = c })
.ToList();