简体   繁体   中英

How to repeat string that is generated using string.Format N times

In C# I have a list:

List<string> ls = new List<string>();
ls.Add("IR");
ls.Add("FR"); // list dynamically generated

and a string:

string langs = "select lang = {0} ";

I want a result like this:

select lang = IR or lang = FR

I found a way:

string result = string.Empty;
foreach (string lng in ls)
    result += string.Format(langs, lng) + "or ";
if (ls.Count > 0)
    result = result.Remove(result.Length - 3, 3);

but I think there is a better way. Any ideas?

Only a single row is needed. Join will save you from additional Count checks:

    result = "Select " + string.Join("or ", ls.Select(l => l = string.Format(langs, l)));

I would change the langs string to the simple beginning of the clause:

string langs = "select lang = ";

List<string> ls = new List<string>() {"IR", "FR"};

and then String.Join the elements separated by " or lang = "

string res = langs + string.Join(" or lang = ", ls);

the output is:

select lang = IR or lang = FR

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