gpt4 book ai didi

c# - 对 DropDownList 进行排序?

转载 作者:太空宇宙 更新时间:2023-11-03 16:21:45 27 4
gpt4 key购买 nike

我很好奇在 C#/ASP.NET 中对 DropDownList 进行排序的最佳途径(更注重简单性,而不是速度或效率)——我看过一些建议,但它们点击效果不佳我。这个下拉菜单按字母顺序给我列表。但我必须随机整理。

注意:我无法控制数据如何进入 DropDownList - 我无法修改 SQL。

public void populateLocationList()
{
DataTable dt_locations = (DataTable)daa_addresses.GetDataByEventLocations(int_eventid);

if (dt_locations != null && dt_locations.Rows.Count > 0)
{
// Populate locations dropdown menu
// Bind locationsList instead of dt_locations
ddl_locations.DataTextField = "Key";
ddl_locations.DataValueField = "Value";
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations);
ddl_locations.DataBind();



string location = "";

// Set the selection based upon the query string
if (Request.QueryString["loc"] != null)
{
location = Request.QueryString["loc"];
locationLbl.Text = Request.QueryString["loc"];
locationID.Value = "-1";
}

if (dt_locations.Rows.Count == 1)
{
location = ddl_locations.Items[0].Text;
locationLbl.Text = location;
}

// Set location in drop down list
int int_foundlocation = 0;
bool foundLocation = false;

foreach (ListItem lsi_item in ddl_locations.Items)
{
if (lsi_item.Text.ToLower().Trim() == location.ToLower().Trim())
{
int_foundlocation = ddl_locations.Items.IndexOf(lsi_item);
foundLocation = true;
break;
}
}

ddl_locations.SelectedIndex = int_foundlocation;

if (ddl_locations.Items.Count == 1)
{
// Make location label visible.
locationLbl.Visible = true;
ddl_locations.Visible = false;
}
else
{
locationLbl.Visible = false;
ddl_locations.Visible = true;
}
//* defualt location S for short courses *//
if (!IsPostBack && !foundLocation)
{
ListItem s = ddl_locations.Items.FindByText("S");
int index = 0;

if (s != null)
{
index = ddl_locations.Items.IndexOf(s);
}

ddl_locations.SelectedIndex = index;
ddl_locations.DataBind();
}
}
}

最佳答案

I have to sort out randomly.

您必须打乱行,可能使用接近此代码的内容(从 @configurator's answer 借来的):

internal static class Extensions
{
internal static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length - 1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
// we don't actually perform the swap, we can forget about the
// swapped element because we already returned it.
}

// there is one item remaining that was not returned - we return it now
yield return elements[0];
}
}

假设 RemoveDuplicateLocations 返回一个 DataTable,您的代码的绑定(bind)部分应该更改为:

        ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations)
.AsEnumerable()
.Shuffle(new Random())
.CopyToDataTable();

关于c# - 对 DropDownList 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com