Search code examples
c#linqsuperpower

Is there way to simplify a LINQ statement using if-else statement in c#


I have a LINQ expression that works but I wanted to make it simpler and cleaner.

var tryCatchTerminator = true;

return tryCatchTerminator
            ? from varKeyword in MatchToken(SyntaxKind.VarKeyword)
            from declarations in ParseVarDeclarationClause.AtLeastOnceDelimitedBy(MatchToken(SyntaxKind.Comma))
            from terminator in MatchToken(SyntaxKind.SemiColon).OptionalOrDefault()
            select (StatementSyntax) new VarDeclarationStatement(varKeyword, declarations, terminator)
            : from varKeyword in MatchToken(SyntaxKind.VarKeyword)
            from declarations in ParseVarDeclarationClause.AtLeastOnceDelimitedBy(MatchToken(SyntaxKind.Comma))
            select (StatementSyntax) new VarDeclarationStatement(varKeyword, declarations, Token<SyntaxKind>.Empty);

I looked all over the internet for some way to include an if statement inside the LINQ expression where I could stop if some condition is met and return an object... or continue to execute another query if the condition is not met.

Maybe this is obvious but I'm really clueless.


Solution

  • It seems to me that this should work for you:

    return
        from varKeyword in MatchToken(SyntaxKind.VarKeyword)
        from declarations in ParseVarDeclarationClause.AtLeastOnceDelimitedBy(MatchToken(SyntaxKind.Comma))
        from terminator in tryCatchTerminator ? MatchToken(SyntaxKind.SemiColon).OptionalOrDefault() : new[] { Token<SyntaxKind>.Empty } 
        select (StatementSyntax)new VarDeclarationStatement(varKeyword, declarations, terminator);
    

    The key to it working is just giving the from terminator expression a single element array to return the empty token if tryCatchTerminator is false.