alternative method of creating string from list - c#

Have such function, which creates string from List of ids
I try to run it in 50 threads, and after 30 seconds it hangs app
public string genText(List<string> list)
{
string text = #"{""text"":""";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += "!" + " ";
else
text += "!" + #""", ";
}
text += #"""start"":[";
for (int i = 0, lim = -2; i < list.Count; i++)
{
lim += 2;
if (i < list.Count - 1)
text += #"""" + lim + #""",";
else
text += #"""" + lim + #"""], ";
}
text += #"""end"":[";
for (int i = 1, lim = -1; i < list.Count + 1; i++)
{
lim += 2;
if (i < list.Count)
text += #"""" + lim + #""",";
else
text += #"""" + lim + #"""], ";
}
text += #"""type"":[";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += #"""USER"",";
else
text += #"""USER""], ";
}
text += #"""objectId"":[";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += #"""" + list[i] + #""",";
else
text += #"""" + list[i] + #"""]}";
}
return text;
}
What i­­­­­­­­­­­­­­s the best (alternative) way of writing such functio­­­­­­­­­­­­­­­­­­­­­­­n?
Expected result: {"text":"! ! ! ! ! ! ! ! ! ! ! ! ! ! !", "start":["0","2","4","6","8","10","12","14","16","18","20","22","24","26","28"], "end":["1","3","5","7","9","11","13","15","17","19","21","23","25","27","29"], "type":["USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER"], "objectId":["524231066205","363249609235","509321690322","551832845250","273337925148","553378679618","552270073142","256641407","545454406232","548096729194","555315805314","553271555117","573655339037","518779453704","486606264340"]}

Instead of concatenating strings it is much more efficient to use the StringBuilder class.
public string genText(List<string> list)
{
StringBuilder text = new StringBuilder();
text.Append(#"{""text"":""");
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text.Append("!" + " ");
...
return text.ToString();
}
but as other have mentioned in the comments, use a Json library if you want to create Json data.

Related

C#, Windows application, draw a square with side N

for school practice I have to make a windows application in C# that takes a input number and draws a square of X's with side N. I have to do it with a loops and i can't use any preset commands. (For example math.pow i cannot use) (I've included a picture of the assignment.) I've already mode this program in a console application and there it worked fine.
I think that i'm very close of solving it but can't figure out what the last step is. I would love to know what i'm missing and how i should solve this.
See the assignment
This is my code now:
int n;
n = int.Parse(txt_input.Text);
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text = "X";
lbl_output.Text = "\n";
}
//middel part
for (int i = 0; i < n - 2; i++)
{
lbl_output.Text = "X";
for (int j = 0; j < n - 2; j++) lbl_output.Text = " ";
lbl_output.Text = "X";
lbl_output.Text = "\n";
}
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text = "X";
lbl_output.Text = "\n";
}
Try this:
int n = int.Parse(txt_input.Text);
var sb = new StringBuilder();
for (int j = 0; j < n; j++)
{
sb.Append('X');
}
sb.AppendLine();
for (int i = 0; i < n - 2; i++)
{
sb.Append('X');
for (int j = 0; j < n - 2; j++)
{
sb.Append(' ');
}
sb.Append('X');
sb.AppendLine();
}
for (int j = 0; j < n; j++)
{
sb.Append('X');
}
lbl_output.Text = sb.ToString();
Try this;
int n = int.Parse(txt_input.Text);
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text += "X";
}
lbl_output.Text += "\n";
//middel part
for (int i = 0; i < n - 2; i++)
{
lbl_output.Text += "X";
for (int j = 0; j < n - 2; j++)
lbl_output.Text += " ";
lbl_output.Text += "X";
lbl_output.Text += "\n";
}
//upper part
for (int i = 0; i < n; i++)
{
lbl_output.Text += "X";
}
You forget to use += which will append the text with the previous assigned text. Also you had some unnecessary new lines in your code.
Need to append to the string. There's a couple ways of doing this. Tho '+=' should work fine. += is short for variable = variable + newValue
int n = int.Parse(txt_input.Text);
string output = "";
for(int x = 0; x < n; x++) //rows
{
if (x == 0 || x == n-1) //first / last row all x
for(int y = 0; y < n; y++)
{
output += "x";
}
else //other rows
for(int y = 0; y < n; y++)
{
output += (y == 0 || y == n - 1) ? "x" : " "; //if first or last column "X" else " "
}
output += "\n"; //at the end of each row a return
}
lbl_output.Text = output;
You can see it run in the browser here: https://dotnetfiddle.net/wiYfjX
Use two loops. One for the width of the square and one for the height of the square.
Give this a try and replace the parameter from what is in the txt_input control. (Just place the function whereever you want in your code (button_click for example) instead of the form load.
private void Form1_Load(object sender, EventArgs e)
{
lblOutput.Text = GenerateSquare(5);
}
private string GenerateSquare(int n)
{
string square = "";
for (int w = 0; w < n; w++)
{
for (int h = 0; h < n; h++)
{
// top or bottom line
if (w == 0 || w == n - 1)
{
square += "x";
}
else // sides
{
if (h == 0 || h == n - 1)
{
square += "x";
}
else square += " ";
}
// change line
if (h == n - 1)
square += "\n";
}
}
return square;
}

Check next loop iteration data unless at end of loop c#

I'm making a program which is creating an ASCII image. Based on the asterix input it produces different things. To start I'm making a basic outline however I have an issue where I cannot add something when checking last for loop iteration.
Method code:
private List<string> DrawOutline(List<string> inputLines)
{
List<string> output = new List<string>();
int door = r.Next(0, inputLines.Last().Length);
for (int li = 0; li < inputLines.Count; li++)
{
char[] curLine = inputLines[li].ToCharArray();
string outputLine1 = string.Empty;
string outputLine2 = string.Empty;
for (int i = 0; i < curLine.Length -1; i++)
{
Console.WriteLine(curLine[i]);
if (curLine[i] == '*')
{
outputLine1 += "+---";
outputLine2 += "| ";
}
else
{
outputLine1 += " ";
outputLine2 += " ";
}
if(li < curLine.Length - 1)
{
if (curLine[i] == '*' && curLine[i + 1] != '*')
{
outputLine1 += "+";
outputLine2 += "|";
}
}
}
output.Add(outputLine1);
output.Add(outputLine2);
}
return output;
}
When I run this, it works fine however will not add '+' and '|' to the last line of outputLines. This is because the line :
if(li < curLine.Length -1)
However without the -1 it will throw an exception because I am using [i+1] to decide something. Is there a way to check only if it won't throw an exception?
you can check if the end of the array has been reached by using the OR ( || ) statement. If the first statement of the OR statement returns true, the second is not checked. This is called short-circuiting. No error should be thrown in this case.
private List<string> DrawOutline(List<string> inputLines)
{
List<string> output = new List<string>();
int door = r.Next(0, inputLines.Last().Length);
for (int li = 0; li < inputLines.Count; li++)
{
char[] curLine = inputLines[li].ToCharArray();
string outputLine1 = string.Empty;
string outputLine2 = string.Empty;
for (int i = 0; i < curLine.Length -1; i++)
{
Console.WriteLine(curLine[i]);
if (curLine[i] == '*')
{
outputLine1 += "+---";
outputLine2 += "| ";
}
else
{
outputLine1 += " ";
outputLine2 += " ";
}
if (curLine[i] == '*' && (curLine.Length == i+1 || curLine[i + 1] != '*'))
{
outputLine1 += "+";
outputLine2 += "|";
}
}
output.Add(outputLine1);
output.Add(outputLine2);
}
return output;
}
Change if (li < curLine.Length - 1) to if (i < curLine.Length - 1)

How do I can optimize inserting/replacement element in to the List<string>

I have some code:
var result = new List<string>;
...
for (var i = 0; i < level; ++i)
if (result.ElementAtOrDefault(i) == null)
result.Insert(i, " " + positions[i]);
else
result[i] += " " + positions[i];
if (result.ElementAtOrDefault(level) == null)
result.Insert(level, " " + currentPosition);
else
result[level] += " " + currentPosition;
Can I do this without checking element for null from i-position? I need to add a part of string in i-position. But I have "ArgumentOutOfRangeException" if element wasn't created. Also method "insert" don't replace the element but push back it.
I tried to get data from "ArgumentOutOfRangeException" (which index called this exception) but I've failed.
You can reduce using ElementAtOrDefault with adding some condition like this
int i;
for (i = 0; i < level && i < result.Count; ++i){
//change existing items
result[i] += " " + positions[i];
}
for (int j = 0, countAdd = level - result.Count; j < countAdd; ++j)
//add new items
result.Add(" " + positions[i+j]);
//add current
if (level >= result.Count)
result.Add(" " + currentPosition);
else
result[level] += " " + currentPosition;

How to create a loop for the following case?

/html/body/table/tr[1]/td[2]
/html/body/table/tr[1]/td[4]
/html/body/table/tr[3]/td[2]
/html/body/table/tr[3]/td[4]
/html/body/table/tr[5]/td[2]
/html/body/table/tr[5]/td[4]
So, the index of tr[ ] would be odd numbers, and td[ ] would always be either 2 or 4.
for(int i = 1; i < bound; i += 2) {
for(int j = 2; j <= 4; j += 2) {
Console.WriteLine(
String.Format("/html/body/table/tr[{0}]/td[{1}]", i, j)
);
}
Console.WriteLine();
}
You could do something as simple as
for(tr = 1; tr < maxodd+1; tr += 2;)
{
//pseudoimplementation
/html/bod/table/tr[tr]/td[2]
/html/bod/table/tr[tr]/td[4]
}
The most naive case:
for(int i = 1; i < 6; i += 2) {
Console.WriteLine("html/body/table/tr[" + i + "]/td[2]");
Console.WriteLine("html/body/table/tr[" + i + "]/td[4]");
}

Get the index while looping

Is it possible to get the current index while looping?
for (int i = 0; i < DGV.Rows.Count - 2; i++)
{
myValue = DGV.CurrentRow.Index + " " + DGV.Rows[i].Cells[1].Value.ToString();
}
But I have in output :
0 First
0 Second
0 ...
I want to get :
1 First
2 Second
3 ...
Thanks.
for (int i = 0; i < DGV.Rows.Count - 2; i++)
{
myValue = (i + 1).ToString() + " " + DGV.Rows[i].Cells[1].Value.ToString();
}
BTW: I'd prefer:
for (int i = 0; i < DGV.Rows.Count - 2; i++)
{
myValue = String.Format("{0} {1}", i + 1, DGV.Rows[i].Cells[1].Value);
}
It's the index just i+1 in this case?
Try:
myValue = (i+1) + " " + DGV.Rows[i].Cells[1].Value.ToString();
you can do this way also
for (int i = 1; i < DGV.Rows.Count - 1; i++)
{
myValue = i.ToString() + " " + DGV.Rows[i-1].Cells[1].Value.ToString();
}

Categories

Resources