简体   繁体   中英

Sort List<string > by Leading Numbers

I am having trouble properly sorting my list based on the leading number. When I sort, it starts with 1, then goes to 10, 11, etc.

I am trying to sort the following in order:

1 | Text One
10 | Text Two
11 | Text Three

The method I'm trying to sort is here:

finalnoteslist = finalnoteslist.OrderBy(num => num).ToList();

        System.Text.StringBuilder clipData = new System.Text.StringBuilder();

        foreach (object value in finalnoteslist)
        {
            clipData.AppendLine(value.ToString());
        }
        Clipboard.Clear();
        Clipboard.SetText(clipData.ToString());
        MessageBox.Show(clipData.ToString() + Environment.NewLine + "NOTES COPIED TO CLIPBOARD. CONTROL + V TO PASTE IN DRAWING");            
    }

    int CompareStringBuilders(System.Text.StringBuilder a, System.Text.StringBuilder b)
    {
        for (int i = 0; i < a.Length && i < b.Length; i++)
        {
            var comparison = a[i].CompareTo(b[i]);
            if (comparison != 0)
                return comparison;
        }

        return a.Length.CompareTo(b.Length);
    }

You split each item by its seperator | and parse the first part into a int value. Then you sort those.

List<string> finalnoteslist = new List<string>() 
                             { "1 | Text One",
                               "10 | Text Two", 
                               "11 | Text Three" 
                             };
finalnoteslist = finalnoteslist.OrderBy(x => int.Parse(x.Split('|').First())).ToList();

You could use string.Split to split and get the leading integer, which can be used to sort your list.

finalnoteslist = finalnoteslist.OrderBy(x=> int.Parse(x.Split('|')[0])).ToList();

Try this Demo

To Sort the List in-place:

List<string> strings = new List<string>()
{
    "1 | Text One", "12 | Text Two", "100 | Text Three", "2 | Text Four"
};

Func<string, int> getNumber = (str) => Int32.Parse(str.Split('|').FirstOrDefault());

strings.Sort((y, x) => getNumber(y) - getNumber(x));

To Sort using Linq (creates a new List):

strings = strings.OrderBy(x => convertFunction(x)).ToList();

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