How can I use C# to sort values numerically?

前端 未结 9 1635
醉话见心
醉话见心 2021-02-20 03:20

I have a string that contains numbers separated by periods. When I sort it appears like this since it is a string: (ascii char order)

3.9.5.2.1.1
3.9.5.2.1.10
3.         


        
9条回答
  •  误落风尘
    2021-02-20 03:46

    Split each string by '.', iterate through the components and compare them numerically.

    This code also assumes that the number of components is signficant (a string '1.1.1' will be greater than '2.1'. This can be adjusted by altering the first if statement in the Compare method below.

        int Compare(string a, string b)
        {
            string[] aParts = a.Split('.');
            string[] bParts = b.Split('.');
    
            /// if A has more components than B, it must be larger.
            if (aParts.Length != bParts.Length)
                return (aParts.Length > bParts.Length) ? 1 : -1;
    
            int result = 0;
            /// iterate through each numerical component
    
            for (int i = 0; i < aParts.Length; i++)
                if ( (result = int.Parse(aParts[i]).CompareTo(int.Parse(bParts[i]))) !=0 )
                    return result;
    
            /// all components are equal.
            return 0;
        }
    
    
    
        public string[] sort()
        {
            /// initialize test data
            string l = "3.9.5.2.1.1\n"
            + "3.9.5.2.1.10\n"
            + "3.9.5.2.1.11\n"
            + "3.9.5.2.1.12\n"
            + "3.9.5.2.1.2\n"
            + "3.9.5.2.1.3\n"
            + "3.9.5.2.1.4\n";
    
            /// split the large string into lines
            string[] arr = l.Split(new char[] { '\n' },StringSplitOptions.RemoveEmptyEntries);
            /// create a list from the array
            List strings = new List(arr);
            /// sort using our custom sort routine
            strings.Sort(Compare);
            /// concatenate the list back to an array.
            return strings.ToArray();
        }
    

提交回复
热议问题