开发者

C# String manipulation for Dynamic Query

开发者 https://www.devze.com 2023-01-12 07:20 出处:网络
I have a string it contains can contains either of (1) strQuery = \"TempTable.Group_No IN ()\"; (2) strQuery = \"TempTable.Group_No IN (1,2,3,4,....)\";

I have a string

it contains can contains either of (1)

 strQuery = "TempTable.Group_No IN ()";

(2)

strQuery = "TempTable.Group_No IN (1,2,3,4,....)";

My task is if it contains "TempTable.Group_No IN ()", (i.e) IN CLAUSE without data

i have to replace the string (IN() with IN (NULL)) with "TempTable.Group_No IN (NU开发者_开发知识库LL)"

How to perform it in C#?


How about...

strQuery = strQuery.Replace("()", "(NULL)");

... or is that a bit too simple?


I don't know how much you have to worry about the empty parenthesis in other areas, but you can use this to have greater certainty that you're replacing the right thing.

strQuery = strQuery.Replace("IN ()", "IN (NULL)");


I'm assuming the input is an array of integers for the solution below. Try this out as a console app:

static void Main(string[] args)
{
    int[] ids1 = new int[] { 1, 2, 3, 4, 5 };
    int[] ids2 = new int[] {};

    Console.WriteLine(FormatQuery(ids1));
    Console.WriteLine(FormatQuery(ids2));           
}

static string FormatQuery(int[] ids)
{
    return string.Format("TempTable.Group_No IN ({0})", 
        ids.Length > 0 ? string.Join(",", ids) : "NULL");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消