Sort selected text from Visual Studio context menu

A nice AddOn for Visual Studio is Code Maid

You select some lines and chose from Context Menu "Sort Lines"

enter image description here

And voilá, your lines are sorted nicely in alphabetical order:

enter image description here


Edit: Note that this solution does not work on VS2013 or higher, since support for macros was removed.

You don't necessarily need to code a VS addin to do this: Visual Studio has macros built in. To get started, use Tools, Macros, Record Temporary Macro.

Here's a 'Sort Lines' command I hacked together based on the code that Record Temporary Macro gave me:

Imports System
Imports EnvDTE

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

VS 2019 & VS 2022:

  1. Select lines. The last selected line is where the cursor is - the line is taken into account even if it is empty and there is no visible selection.
  2. Shift + Alt + L, Shift + Alt + S => Ascending sort.
  3. Shift + Alt + L, Shift + Alt + S (same selection same keys) => Descending sort.

The command can also be invoked from menu (@sharpener): Edit | Advanced | Sort Lines


Just found a good free addon: Menees VS Tools 2012 (or 2010 ver) - does exactly that and a few more text tricks. There was a few minor negatives when I installed it, but after leaving a comment on the review page it got fixed within days. Waay to go! =)

There is a 2017 version now: Menees VS Tools 2017