[英][C#]Sort items in listbox
我正在使用正則表達式來解析 HTML:
private void button2_Click(object sender, EventArgs e)
{
string html = textBox1.Text;
foreach (Match matcha in Regex.Matches(html, @"<(.*?)>(.*?)</(.*?)>"))
{
listBox1.Items.Add(matcha.Index.ToString() + matcha);
}
foreach (Match matchb in Regex.Matches(html, @"<input type=(.*?)>"))
{
listBox1.Items.Add(matchb.Index.ToString() + matchb);
}}
按下button2
, listbox1
具有以下項目:
25...
29...
27...
我想要預期的輸出
25 ...
27...
29...
我該怎么辦?
將您的項目添加到列表中,對其進行排序,然后制作您的 ListBox 的排序列表源:
private void button2_Click(object sender, EventArgs e)
{
string html = textBox1.Text;
List<String> tmp = new List<String>();//Add this
foreach (Match matcha in Regex.Matches(html, @"<(.*?)>(.*?)</(.*?)>"))
{
tmp.Add(matcha.Index.ToString() + matcha);//Change this line
}
foreach (Match matchb in Regex.Matches(html, @"<input type=(.*?)>"))
{
tmp.Add(matchb.Index.ToString() + matchb);//Change this one too
}
var sorted = list.OrderBy(x => PadNumbers(x));//Add this line
listBox1.Datasource = sorted;//and this
}
當PadNumbers
定義為:
public static string PadNumbers(string input)
{
return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}
這應該像“自然排序”那樣對所有數字進行排序。 因此,如果您的數字是8, 90, 10
,則此腳本會將其排序為8, 10, 90
,而正常排序將返回10, 8, 90
。
都清楚了嗎?
在添加項目之前將 sorted 屬性設置為 true:
listBox1.sorted = true;
private void button1_Click(object sender, EventArgs e)
{
int num_items = listBox1.Items.Count;
object[] items = new object[num_items];
listBox1.Items.CopyTo(items, 0);
// Sort them by their contained numeric values.
items = SortNumericItems(items);
// Display the results.
listBox1.Sorted = false;
listBox1.DataSource = items;
}
private object[] SortNumericItems(object[] items)
{
// Get the numeric values of the items.
int num_items = items.Length;
const string float_pattern = @"-?\d+\.?\d*";
double[] values = new double[num_items];
for (int i = 0; i < num_items; i++)
{
string match = Regex.Match(
items[i].ToString(), float_pattern).Value;
double value;
if (!double.TryParse(match, out value))
value = double.MinValue;
values[i] = value;
}
// Sort the items array using the keys to determine order.
Array.Sort(values, items);
return items;
}
按下 button1 時,listbox1 具有以下項目:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.