Venkat
Venkat

Reputation: 2156

Code optimisation for foreach in C#

Code:

string testquestions = "1,2,100,3,4,101,98,99";
string[] qidarray = testquestions.Split(',');

StringBuilder sb = new StringBuilder();

foreach (string s in qidarray)
{
    sb.Append(String.Format(@"({0}),",s));
}

string output= sb.ToString().Substring(0, sb.ToString().Length - 1);

Desired output =

(1),(2),(100),(3),(4),(101),(98),(99)

The code works. I want to know is this the best way for achieving the result. Is there a better way to achieve the desired result?

Is there a way not to use a foreach loop?

Upvotes: 1

Views: 122

Answers (2)

user1672994
user1672994

Reputation: 10839

This would do the trick. The code is first splitting the string and using linq, formatting to desired output.

var strToPrint = string.Join(",", testquestions.Split(',')
                       .Select(s => string.Format(@"({0})", s)));

Console Output

Console.WriteLine(string.Join(",", testquestions.Split(',')
                        .Select(s => string.Format(@"({0})", s))));

You can check the live fiddle here - https://dotnetfiddle.net/4zBqMf

Edit :

As suggested by @paparazzo, you can use string interpolation to write the syntax as

var strToPrint = string.Join(",", testquestions.Split(',').Select(s => $"({s})"));

Live fiddle - https://dotnetfiddle.net/xppLH2

Upvotes: 8

user3389475
user3389475

Reputation: 174

Here are some other ways using Replace.

string testquestions = "1,2,100,3,4,101,98,99";

string result = new StringBuilder("(" + testquestions + ")").Replace(",", "),(").ToString();

string result1 = "(" + testquestions.Replace(",", "),(") + ")";

string result2 = "(" + new Regex(",").Replace(testquestions, "),(") + ")";

Upvotes: 1

Related Questions