对我的下拉列表进行排序的任何更好的方法

问题描述 投票:1回答:3

我用英语检索到国家名称后,将国家名称转换为本地化版本,我需要再次对这些名称进行排序,因此我使用了SortDropDownList。在这里,对DropDownList项目进行排序后,我丢失了我设置的PrivacyOption属性。

有人可以建议解决方案对我的DropDownList进行排序,同时还保留PrivacyOption属性吗?

我正在将asp.net4.0和C#用作CodeBehind

int iCount = 1;

//fetch country names in English
List<CountryInfo> countryInfo = ReturnAllCountriesInfo();

foreach (CountryInfo c in countryInfo)
{
    if (!string.IsNullOrEmpty(Convert.ToString(
        LocalizationUtility.GetResourceString(c.ResourceKeyName))))
    {
        ListItem l = new ListItem();
        l.Text = Convert.ToString(
                    LocalizationUtility.GetResourceString(c.ResourceKeyName));
        l.Value = Convert.ToString(
                    LocalizationUtility.GetResourceString(c.ResourceKeyName));
        //True /False*
        l.Attributes.Add("PrivacyOption", *Convert.ToString(c.PrivacyOption));

        drpCountryRegion.Items.Insert(iCount, l);
        iCount++;
    }
    //sorts the dropdownlist loaded with country names localized language
    SortDropDownList(ref this.drpCountryRegion);  
}

以及SortDropDownList项目的代码:

private void SortDropDownList(ref DropDownList objDDL)
{
    ArrayList textList = new ArrayList();
    ArrayList valueList = new ArrayList();

    foreach (ListItem li in objDDL.Items)
    {
        textList.Add(li.Text);

    }

    textList.Sort();

    foreach (object item in textList)
    {
        string value = objDDL.Items.FindByText(item.ToString()).Value;
        valueList.Add(value);
    }
    objDDL.Items.Clear();

    for (int i = 0; i < textList.Count; i++)
    {
        ListItem objItem = new ListItem(textList[i].ToString(), 
               valueList[i].ToString());              

        objDDL.Items.Add(objItem);

    }
}
c# asp.net-4.0
3个回答
3
投票

在填充DropDownList之前先对数据进行排序。

IEnumerable<Country> sortedCountries = countries.OrderBy(
                c => LocalizationUtility.GetResourceString(c.ResourceKeyName));

foreach (Country country in sortedCountries)
{
    string name = LocalizationUtility.GetResourceString(country.ResourceKeyName);
    if (!string.IsNullOrEmpty(name))
    {
        ListItem item = new ListItem(name);
        item.Attributes.Add(
             "PrivacyOption", 
             Convert.ToString(country.PrivacyOption));
        drpCountryRegion.Items.Add(item);
    }
}

0
投票

我不确定我是否了解您的SortDropDownList方法的实现方式。但是,我建议使用List >绑定到您的下拉菜单。您可以在键值对中使用英语部分和本地部分并进行相应的排序。


0
投票

您是否考虑过将信息排序为SortedDictionary而不是List

© www.soinside.com 2019 - 2024. All rights reserved.