简体   繁体   中英

How to sort rich text box in ascending order using c#

I want get out put like 1.2.3.4.5.. but in this code I got values like 1,10,100,101.. plz help me friends

private void btn_load_Click_1(object sender, EventArgs e)
{
    {
        if (textBox1.Text != "")
        {
            richTextBox1.Clear();
            string tt = @"" + textBox1.Text;
            String sdira = @"" + textBox1.Text;
            string[] arrays = Directory.GetFiles(sdira, "*", SearchOption.AllDirectories)
              .Select(x => Path.GetFileName(x))
              .ToArray();// get only file name and extention
            foreach (string name in arrays)
            {
                //StringBuilder sb = new StringBuilder();
                richTextBox1.Text += name + "\n";
                //i want get out put like 1.2.3.4.5.. 
                //but in this code i got values like 1,10,100,101.. 
                //plz help me friends[first img is my current out put][1]
            }
        }
    }

Sample

If you want sort the strings as numbers instead of lexicographically you have to parse them:

var orderedFiles = Directory.EnumerateFiles(sdira, "*", SearchOption.AllDirectories)
    .Select(x => new { file = x, nameNumber = Path.GetFileName(x).TryGetInt32() })
    .Where(x => x.nameNumber.HasValue)
    .OrderBy(x => x.nameNumber.Value)
    .Select(x => x.file); // or x.nameNumber.Value is you want the number

Here's the parse extension method is use in LINQ queries:

public static int? TryGetInt32(this string item, IFormatProvider formatProvider = null, NumberStyles nStyles = NumberStyles.Any)
{
    if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
    int i = 0;
    bool success = int.TryParse(item, nStyles, formatProvider, out i);
    if (success)
        return i;
    else
        return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM