0

This one perfectly works:

($"SELECT * FROM {Table} WHERE Hex = 11 {(isConfirmed ? " AND UserId<>5" : string.empty)}";

Nevertheless besides static 5 value i want to put variable there. I tried to change as follows nevertheless something is wrong:

($"SELECT * FROM {Table} WHERE Hex = 11 {(isConfirmed ? " AND UserId<>"{myVariable} : string.empty)}";

What i am doing wrong?

Pavel Anikhouski
  • 19,922
  • 12
  • 45
  • 57
Arie
  • 1,680
  • 3
  • 20
  • 46

2 Answers2

2

This should work:

string query = $"SELECT * FROM {Table} WHERE Hex = 11 {(isConfirmed ? $" AND UserId<>{myVariable}" : string.Empty)}";
SomeBody
  • 6,564
  • 2
  • 15
  • 30
2

You should add an interpolation character $ before inner " AND UserId<>{myVariable}" string to use an interpolation expression inside this string

var isConfirmed = true;
var Table = "test";
var myVariable = 5;
var str = $"SELECT * FROM {Table} WHERE Hex = 11 {(isConfirmed ? $" AND UserId<>{myVariable}" : string.Empty)}";

It'll give you

SELECT * FROM test WHERE Hex = 11 AND UserId<>5

Pavel Anikhouski
  • 19,922
  • 12
  • 45
  • 57
  • Speculating, probably because it's the same as an answer posted two minutes earlier. – GSerg Apr 08 '20 at 10:34
  • @GSerg First point - while posting and typing an answer I didn't check an updates of the page, second point - a code explanation. According to the site rules code-only answers are not considered as a good ones – Pavel Anikhouski Apr 08 '20 at 10:38