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
  • 21,776
  • 12
  • 51
  • 66
Arie
  • 3,041
  • 7
  • 32
  • 63

2 Answers2

2

This should work:

string query = $"SELECT * FROM {Table} WHERE Hex = 11 {(isConfirmed ? $" AND UserId<>{myVariable}" : string.Empty)}";
SomeBody
  • 7,515
  • 2
  • 17
  • 33
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
  • 21,776
  • 12
  • 51
  • 66
  • 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