我的工作中有一些使用ASP.net的代码(我从未接触过),但我需要对其进行排序。这是我需要按Dscrp排序的ListBox:
foreach (InteractiveInfo template in ddlsource)
{
Product thisProduct = FindProduct(template.UProductId);
if (thisProduct != null)
{
ddlProducts.Items.Add(
new ListItem(
string.Format("{0} ({1})", thisProduct.Dscrp, thisProduct.UProductId),
template.UProductId.ToString(CultureInfo.InvariantCulture)));
}
}
ddlProducts.DataBind();
}
我找到了这个链接:
https://gist.github.com/chartek/1655779
所以我尝试在最后加上这个:
ddlProducts.Items.Sort();
但它只是给了我这个错误:
不包含'Sort'的定义
答案 0 :(得分:1)
如果您的应用程序使用的是.NET 3.5或更高版本,请查看MSDN: Extension Methods。
您提供的tutorial link正在使用扩展方法概念,其中Sort()
方法被装饰到ListItemCollection
(即ddlProducts.Items
)类型。
扩展方法应该在非泛型静态类中定义。所以教程缺少一个类定义。您可以尝试:
public static class ExtensionsMethods //Notice the static class
{
public static void Sort(this ListItemCollection items)
{
//... Implement rest of logic from the tutorial
}
// Other extension methods, if required.
}
希望这对你有所帮助。
答案 1 :(得分:0)
使用类似这样的东西并不完美,但根据您的要求更新
public static void Sort(this ListItemCollection items)
{
var itemsArray = new ListItem[items.Count];
items.CopyTo(itemsArray,0);
Array.Sort(itemsArray, (x, y) => (string.Compare(x.Value, y.Value, StringComparison.Ordinal)));
items.Clear();
items.AddRange(itemsArray);
}