14

我正在尝试优化 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)绑定到具有相同repeater配置的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();
4

1 回答 1

6

我认为这一行可以替换您的第二个代码块:

CountryOptionsRepeater.DataSource = 
    countriesList
    .Distinct()
    .OrderBy(c => c)
    .Select(c => new { CountryName = c })
    .ToList();
于 2012-10-01T15:45:17.477 回答