【发布时间】:2012-10-01 14:46:02
【问题描述】:
我正在尝试优化 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,配置相同的repeater,从而带来优化?
类似:
//countriesList = countriesList.Distinct<String>().ToList<String>();
//countriesList.Sort();
var noDupsCountriesList = new HashSet<String>(countriesList);
CountryOptionsRepeater.DataMember = "CountryName"; // ??
CountryOptionsRepeater.DataSource = noDupsCountriesList;
CountryOptionsRepeater.DataBind();
this.DataBind();
【问题讨论】:
-
为什么需要 DataTable 或 HashSet?
CountryOptionsRepeater.DataSource = countriesList;不会成功吗? -
可能可以直接绑定到
HashSet<>,但它不会为您提供按字母顺序排序的国家/地区,从您的代码看来这是必要的。 -
@MiMo,谢谢,我会添加
OrderBy语句(假设 HashSet 的initializaiton + OrderBy比调用 List 的Distinct() + ToList() + Sort()优化得多).. -
在这种情况下,
CountryOptionsRepeater.DataSource = countriesList.Distinct().OrderBy(c => c).ToList();,是的,您可以将 DataSource 与任何IEnumerable<>一起使用
标签: c# asp.net .net sharepoint