2012-10-01 30 views
14

我正在尝试优化SharePoint webpart的代码。我有一个中继器控制:HashSet as DataSource

<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)直接结合至与中继器的相同的配置数据源的方式,为了带来优化?

喜欢的东西:

//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

为什么你需要的数据表或HashSet的?会'CountryOptionsRepeater.DataSource = countriesList;'不是做诡计? – paul

+0

直接绑定到'HashSet <>'可能是可能的,但它不会给你按字母顺序排序的国家,你的代码似乎是必要的。 – MiMo

+1

@MiMo,谢谢我将添加'OrderBy'语句(假设HashSet的'initializaiton + OrderBy'比调用List <>的'Distinct()+ ToList()+ Sort()')更优化。 – Annie

回答

6

我觉得这条线可以取代你的代码的第二块:

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

它抛出一个错误:找不到列名'CountryName'。我应该在ascx文件中使用''(因为List没有列标题)? – Annie

+1

如果使用基本类型,DataMember应保留为空。 DataMember旨在指定类型的属性。 – Shelakel