Sorting Text in Visual Studio

Sometimes you need to sort some lines of code in Visual Studio – for instance, if you have a long list of Open XML content types, Open XML relationship types, or elements names, you may want that list to be sorted. Here is a little VB snippet (from stackoverflow) that sorts text.

Sub SortLines()
    Dim Selection As TextSelection = DTE.ActiveDocument.Selection
    Dim Lines() As String = Selection.Text.Replace(Environment.NewLine, Chr(13)).Split(Chr(13))
    DTE.UndoContext.Open("Sort Lines")
    ' Edit - see comments
    ' Selection.Text = String.Join(Environment.NewLine, Lines)
    Selection.Insert(String.Join(Environment.NewLine, Lines))
End Sub

Posting this here so I can find it again easily.

Leave a Comment