简体   繁体   中英

how to sort list with strings containing numbers?

I have a Tlist that contains addresses. When I sort the list, numbers in the address are considered a string, and it doesn't sort correctly. How should I sort the list ascending?

 Dim sortme As List(Of data) = tempdata 'main list containing addresses as strings.
     sortme.Sort(Function(p1 As data, p2 As data) numorder(p1.Value).CompareTo(numorder(p2.Value)))

       Private Function numorder(ByVal str As String)
        Try
            Dim words() As String = str.Split(" "c) 'read string up to first space (for number)
            Return Convert.ToInt32(words(0))
        Catch ex As Exception
        End Try
    End Function

Example of current output:

1001 street name

103 street name

1021 street name

It should be:

103 street name

1001 street name

1021 street name

The idea is to write your own comparer which will firs consider the number prefix and then the string itself. This comparer can be then used anywhere, for instance in LINQ OrderBy() . Here an example in c# see full VB.NET version below.

   public class StreetComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            int indexOfSpaceX = x.IndexOf(' ');
            string numericalPartX = x.Substring(0, indexOfSpaceX);

            int indexOfSpaceY = y.IndexOf(' ');
            string numericalPartY = y.Substring(0, indexOfSpaceY);

            int numberX;
            int numberY;

            if(!int.TryParse(numericalPartX, out numberX) ||
                !int.TryParse(numericalPartY, out numberY))
            {
                //Some code to handle the case where number is missing
                throw new ArgumentException();
            }

            if (numberX!=numberY)
            {
                return numberX-numberY;
            }

            string textPartX = x.Substring(indexOfSpaceX + 1);
            string textPartY = x.Substring(indexOfSpaceY + 1);

            return String.Compare(textPartX, textPartY, true, CultureInfo.CurrentCulture);

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var myStreets = new[] {"01 aaa", "02 bbb"};

            var result = myStreets.OrderBy(s => s, new StreetComparer());
        }
    }

Now a VB.NET version adapted exactly to your use case a List with classes sorted by property:

Public Class StreetComparer
    Implements IComparer(Of String)
    Public Function Compare(x As String, y As String) As Integer
        Dim indexOfSpaceX As Integer = x.IndexOf(" "C)
        Dim numericalPartX As String = x.Substring(0, indexOfSpaceX)

        Dim indexOfSpaceY As Integer = y.IndexOf(" "C)
        Dim numericalPartY As String = y.Substring(0, indexOfSpaceY)

        Dim numberX As Integer
        Dim numberY As Integer

        If Not Integer.TryParse(numericalPartX, numberX) OrElse Not Integer.TryParse(numericalPartY, numberY) Then
            'Some code to handle the case where number is missing
            Throw New ArgumentException()
        End If

        If numberX <> numberY Then
            Return numberX - numberY
        End If

        Dim textPartX As String = x.Substring(indexOfSpaceX + 1)
        Dim textPartY As String = x.Substring(indexOfSpaceY + 1)

        Return [String].Compare(textPartX, textPartY, True, CultureInfo.CurrentCulture)

    End Function
End Class

Public Class Person
    Public Property Value() As String
        Get
            Return m_Value
        End Get
        Set
            m_Value = Value
        End Set
    End Property
    Private m_Value As String

    Public Sub New(value__1 As String)
        Value = value__1
    End Sub
End Class

Class Program
    Private Shared Sub Main(args As String())
        Dim sortme As New List(Of Person)(New () {New Person("1001 street name"), New Person("103 street name"), New Person("1021 street name")})

        Dim result = sortme.OrderBy(Function(p) p.Value, New StreetComparer())

        For Each person As var In result
            Console.WriteLine(person.Value)
        Next
        Console.ReadKey()
    End Sub
End Class

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