C# – Tools to Swap Equations in Code

c

I know this might be trivial to some but when programming say in c# and you have a very large data structure. I usually do assignment via equation for setting value in control and then later do it the reverse way.

Control1.Text = data.value1;
Control2.SelectedValue = data.value2;

Reverse:

data.value1 = Control1.Text;
data.value2 = Control2.SelectedValue;

I was wondering if there is a tool to do this quickly. This is to assume that you have a very large set of values.

Best Answer

You could use Visual Studio Find & Replace to perform the swap. Here's a regular expression pair that will perform the replacement automatically:

Find: ^{:b*}{([^=]+)} += +{([^=]+)};
Replace: \1\3 = \2;

Remember to turn on regular expressions. This will do exactly what you are asking for. This can also be encapsulated into a macro. Here's an example Macro that I put together:

Sub SwapAssignments()
    DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
    DTE.Find.FindWhat = "^{:b*}{([^=]+)} += +{([^=]+)};"
    DTE.Find.ReplaceWith = "\1\3 = \2;"
    DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocumentFunction
    DTE.Find.MatchCase = False
    DTE.Find.MatchWholeWord = False
    DTE.Find.MatchInHiddenText = True
    DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr
    DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
    If (DTE.Find.Execute() = vsFindResult.vsFindResultNotFound) Then
        Throw New System.Exception("vsFindResultNotFound")
    End If
    DTE.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close()
End Sub

...This will simply swap assignments in the current block.