Daniele Sartori
Daniele Sartori

Reputation: 1703

Build a string changing a variable in each loop iteration and joining all of them

I need to build a my sql query which is basically at his core is similar to the following:

select something from {myCurrentTable} where some condition

This query must be repeated N times where N is unknown and put in a union.

I need to change the value of myCurrentTable every iteration so i would do something like this:

foreach(string table in myTables)
{
    queryTot += $"SELECT something from {table} where some condition";
    if(!lastIteration)
       queryTot += " union ";
}

Is there any function i can use to get rid of the explicit loop?

Upvotes: 0

Views: 156

Answers (2)

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

You could use LINQ Select to project the tables into SQL select statements, then string.Join to add a union between each one:

string query = string.Join(
    " union ",
    myTables.Select(table => $"SELECT something from {table} where some condition"));

Using string.Join rather than a manual loop means that the unions are correctly inserted without having to check for the last iteration, or check whether the myTables collection only contains a single item.

Upvotes: 3

Ran Turner
Ran Turner

Reputation: 18096

If you concatenate strings in a loop in an undeterministic count, you should consider using StringBuilder instead of regular String.

Since a string is an immutable data type in C#, when you combine two or more strings, a new string is produced. If you append a series of characters to a string (like in your example), you will recreate the same string in memory multiple times..

An alternative approach is modifying a StringBuilder instance which does not result in the creation of a new instance in memory, hence it's recommended in the case you describe.

Upvotes: 2

Related Questions