Sorting List in C#

后端 未结 7 1643
囚心锁ツ
囚心锁ツ 2020-11-28 12:01

How to sort a List based on the item\'s integer value

The list is like

\"1\"
\"5\"
\"3\"
\"6\"
\"11\"
\"9\"
\"NUM1\"
\"NUM0\"

The r

7条回答
  •  一生所求
    2020-11-28 12:39

    Try writing a small helper class to parse and represent your tokens. For example, without too many checks:

    public class NameAndNumber
    {
        public NameAndNumber(string s)
        {
            OriginalString = s;
            Match match = Regex.Match(s,@"^(.*?)(\d*)$");
            Name = match.Groups[1].Value;
            int number;
            int.TryParse(match.Groups[2].Value, out number);
            Number = number; //will get default value when blank
        }
    
        public string OriginalString { get; private set; }
        public string Name { get; private set; }
        public int Number { get; private set; }
    }
    

    Now it becomes easy to write a comparer, or sort it manually:

    var list = new List { "ABC", "1", "5", "NUM44", "3", 
                                  "6", "11", "9", "NUM1", "NUM0" };
    
    var sorted = list.Select(str => new NameAndNumber(str))
        .OrderBy(n => n.Name)
        .ThenBy(n => n.Number);
    

    Gives the result:

    1, 3, 5, 6, 9, 11, ABC, NUM0, NUM1, NUM44

提交回复
热议问题