Format Multiline code to single line in Visual Stu

2020-06-08 13:34发布

问题:

Is there a keyboard shortcut or fast way to change the below code to a single line in Visual Studio 2013? I also have Resharper installed.

Multi

new XElement("Option",
            new XAttribute("Name", "FileDelete"),
            "1"
        ),

Single

new XElement("Option", new XAttribute("Name", "FileDelete"),"1" ),

回答1:

Just select all the text

and press (control + j)

and it will become 1 line of code



回答2:

I setup find/replace for quick use with a regex expression like so:

(note: I use VS 2015, so your hotkeys may be different)

  1. Use Ctrl+H to open quick find replace.
  2. Make sure the "Use Regular Expressions" button is active/toggled-on, and that you are set to search in "Selection" (Not "Document" or "Entire Solution" or whatever)
  3. Type
    \s+
    and a space ()
    in the "find" and "replace with" boxes respectively.
  4. Press Esc key to exit quick find/replace.
  5. Now, as long as you don't change anything, you can select any text you want to make single line, and use the following hotkey sequence to quickly format it:
    1. Ctrl+H (Open quick find/replace)
    2. Alt+A (Replace any occurrence of 1 or more White Spc chars with a single space.)
    3. Enter (Close the popup window that says "X Occurrences Found")
    4. Esc (Exit quick find/replace and return to your code)

I use this all the time after visual studio does things like implementing interfaces to turn stuff like

public SomeType SomeProperty {
    get {
        throw new NotImplementedException();
    }
    set {
        throw new NotImplementedException();
    }
}

into stuff like

public SomeType SomeProperty { get { return someField; } set { /*Some Simple Set Code*/; } }


回答3:

To make it with ReSharper, you should uncheck the option "Keep existing line breaks" in ReSharper/Options/Code Editing/C#/Formatting style/Line Breaks and Wrapping.

Or just add this line into your .dotSettings

<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_USER_LINEBREAKS/@EntryValue">False</s:Boolean>

Then you could format your code using Code Cleanup Tool (default shortcut is Ctrl+Alt+F) or just by typing semicolons or braces.



回答4:

You can change your VS settings to automatically format code in whatever way you want, then select and retype any line/block-ending character (';' or '}') after the text you want formatted and VS will format it for you.



回答5:

You can accomplish this using CodeMaid. The default keybinding is F3, but the command is called CodeMaid.JoinLines if you want to change it