【问题标题】:HashSet as DataSourceHashSet 作为数据源
【发布时间】: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&lt;&gt;,但它不会为您提供按字母顺序排序的国家/地区,从您的代码看来这是必要的。
  • @MiMo,谢谢,我会添加 OrderBy 语句(假设 HashSet 的 initializaiton + OrderBy 比调用 List 的 Distinct() + ToList() + Sort() 优化得多)..
  • 在这种情况下,CountryOptionsRepeater.DataSource = countriesList.Distinct().OrderBy(c =&gt; c).ToList();,是的,您可以将 DataSource 与任何 IEnumerable&lt;&gt; 一起使用

标签: c# asp.net .net sharepoint


【解决方案1】:

我认为这行代码可以替换你的第二段代码:

CountryOptionsRepeater.DataSource = 
    countriesList
    .Distinct()
    .OrderBy(c => c)
    .Select(c => new { CountryName = c })
    .ToList();

【讨论】:

  • 抛出错误:找不到列名CountryName。我应该在 ascx 文件中使用&lt;HeadingTemplate&gt;(因为列表没有列标题)?
  • 如果使用原始类型,DataMember 应该留空。 DataMember 用于指定类型的属性。
猜你喜欢
  • 1970-01-01
  • 2015-12-02
  • 2015-12-02
  • 2016-08-02
  • 1970-01-01
  • 2021-12-09
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多