简体   繁体   中英

Create string line comma separated

I have 6 bool "categories":

Category0, Category1, Category2, Category3, Category4, Category5.

I also have a "String ListCat" variable. This variable must look like something like:

ListCat = "0,1,2,3,4,5"

Where "0" is displayed if Category0 = true, "1" if category1 = true...

For exemple :

Categorie0 = true;
Catgorie1 = true;
Categorie5 = true;

Then ListCat would be like :

ListCat ="0,1,5"

I have to do this to complete this query :

string StSQL = @"SELECT [Type Jour] FROM CodificationTypesJour where Categorie IN (" + ListCat + ");

How can I do that, with the commas included?

Thanks in advance.

You can create an array of values you want to add to result, then join them using String.Join Method .

For example if you have:

bool category0 = true,
     category1 = true,
     category2 = false,
     category3 = false,
     category4 = false,
     category5 = true;

then you can create an array:

string[] values = 
{
    category0 ? "0" : null,
    category1 ? "1" : null,
    category2 ? "2" : null,
    category3 ? "3" : null,
    category4 ? "4" : null,
    category5 ? "5" : null
};

and the result will be:

var result = string.Join(",", values.Where(s => s != null));

// output: "0,1,5"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM