Reputation: 73
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?
Upvotes: 2
Views: 132
Reputation: 2314
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)));
Upvotes: 2
Reputation: 23732
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
Upvotes: 2