Concatenating List<List<string>> takes a long time [duplicate] - c#

This question already has answers here:
Most efficient way to concatenate strings?
(18 answers)
Make String concatenation faster in C# [duplicate]
(6 answers)
Closed 5 years ago.
What I had tried till Now
string Value ="";
foreach (List<string> val in L1)
{
Value = Value + string.Join(",", val) + " // ";
}
Where L1 is of datatype List <List<strings>>
This Works, But its take almost n half hour to complete
Is there as many fastest and simple way to achieve this.

I'd suggest use StringBuilder instead of concatenations in a loop like that:
StringBuilder builder = new StringBuilder();
foreach (List<string> val in L1)
{
builder.Append(string.Join(",", val) + " // ");
}
string result = builder.ToString();
When concatenating in a loop it needs to copy the string everytime to a new position in memory with the extra allocated memory. StringBuilder prevents that.
You can also refer to:
How to use StringBuilder wisely
How does StringBuilder work?
How the StringBuilder class is implemented? Does it internally create new string objects each time we append?

Related

How to convert an 1D double array to a String [duplicate]

This question already has answers here:
What is the fastest way of converting an array of floats to string? [duplicate]
(5 answers)
Closed 3 months ago.
i am trying to connvert
double[] v = { 5, 4, -8, 2, 6 };
to a String with a method.
I created an method called ToString(double[] v);
and tried to do it with an foreach loop, but every time i insert a double the console gives out system.double instead of the string.
for university i am only allowed to use convert.toString and no parse and i should use it as a method
Thanks for your support.
Benjamin
The correct way to do this would be to use string.Join
var myString = string.Join(", ", myDoubles);
But if you want to do the same thing yourself it is fairly easy to do:
var sb = new StringBuilder();
foreach(var myDouble in myDoubles){
sb.Append(Convert.ToString(myDouble)).Append(",");
}
var myString = sb.ToString();
If you are not allowed to use stringBuilder either you can just concatenate strings instead, just keep in mind that increases the algorithmic complexity, and is not really something you should do, or even teach as an example.

How do I make permanent changes to a variable within for loops so that the variable doesn't reset every iteration? [duplicate]

This question already has answers here:
string.Replace (or other string modification) not working
(4 answers)
Closed 3 years ago.
I want to replace characters in a string iteratively using the string.Replace() function in a for loop however every iteration the string itself resets and no changes made in the previous loop stay. Ending up in the string undergoing no changes overall.
I've tried making the string a class member but that didn't work,
static void Main(string[] args)
{
int i;
string strOne = "abcdefg";
for (i=0; i < (strOne.Length - 1); i++)
{
string c = Convert.ToString(strOne[i]);
strOne.Replace(c, "1");
}
}
I expect the output of 1111111 but instead i get abcdefg.
When you call string.Replace(), it does not modify the string itself. Instead, it returns the string with the replaced characters. Therefore, you need to do this: strOne = strOne.Replace(c, "1");

Replace character at specific index in List<string>, but indexer is read only [duplicate]

This question already has answers here:
Is there an easy way to change a char in a string in C#?
(8 answers)
Closed 5 years ago.
This is kind of a basic question, but I learned programming in C++ and am just transitioning to C#, so my ignorance of the C# methods are getting in my way.
A client has given me a few fixed length files and they want the 484th character of every odd numbered record, skipping the first one (3, 5, 7, etc...) changed from a space to a 0. In my mind, I should be able to do something like the below:
static void Main(string[] args)
{
List<string> allLines = System.IO.File.ReadAllLines(#"C:\...").ToList();
foreach(string line in allLines)
{
//odd numbered logic here
line[483] = '0';
}
...
//write to new file
}
However, the property or indexer cannot be assigned to because it is read only. All my reading says that I have not set a setter for the variable, and I have tried what was shown at this SO article, but I am doing something wrong every time. Should what is shown in that article work? Should I do something else?
You cannot modify C# strings directly, because they are immutable. You can convert strings to char[], modify it, then make a string again, and write it to file:
File.WriteAllLines(
#"c:\newfile.txt"
, File.ReadAllLines(#"C:\...").Select((s, index) => {
if (index % 2 = 0) {
return s; // Even strings do not change
}
var chars = s.ToCharArray();
chars[483] = '0';
return new string(chars);
})
);
Since strings are immutable, you can't modify a single character by treating it as a char[] and then modify a character at a specific index. However, you can "modify" it by assigning it to a new string.
We can use the Substring() method to return any part of the original string. Combining this with some concatenation, we can take the first part of the string (up to the character you want to replace), add the new character, and then add the rest of the original string.
Also, since we can't directly modify the items in a collection being iterated over in a foreach loop, we can switch your loop to a for loop instead. Now we can access each line by index, and can modify them on the fly:
for(int i = 0; i < allLines.Length; i++)
{
if (allLines[i].Length > 483)
{
allLines[i] = allLines[i].Substring(0, 483) + "0" + allLines[i].Substring(484);
}
}
It's possible that, depending on how many lines you're processing and how many in-line concatenations you end up doing, there is some chance that using a StringBuilder instead of concatenation will perform better. Here is an alternate way to do this using a StringBuilder. I'll leave the perf measuring to you...
var sb = new StringBuilder();
for (int i = 0; i < allLines.Length; i++)
{
if (allLines[i].Length > 483)
{
sb.Clear();
sb.Append(allLines[i].Substring(0, 483));
sb.Append("0");
sb.Append(allLines[i].Substring(484));
allLines[i] = sb.ToString();
}
}
The first item after the foreach (string line in this case) is a local variable that has no scope outside the loop - that’s why you can’t assign a value to it. Try using a regular for loop instead.
Purpose of for each is meant to iterate over a container. It's read only in nature. You should use regular for loop. It will work.
static void Main(string[] args)
{
List<string> allLines = System.IO.File.ReadAllLines(#"C:\...").ToList();
for (int i=0;i<=allLines.Length;++i)
{
if (allLines[i].Length > 483)
{
allLines[i] = allLines[i].Substring(0, 483) + "0";
}
}
...
//write to new file
}

How do I assign string array values into single variable [duplicate]

This question already has answers here:
Convert array of integers to comma-separated string
(5 answers)
Closed 6 years ago.
I have managed to get a list of names from a database, join the first and last name, put these names into an array so that they can be called up in say a MessageBox. How do I place the values from a dynamic string array into a string variable preferably separated by commas.
Here is my code so far:
string[] array = new string[size];
for (int i = 0; i < size; i++)
{
array[i] = Join(fullname);
}
foreach (string i in array)
{
MessageBox.Show(i);
}
Use string.Join:
var myString = string.Join(",", array);

Add into string field [duplicate]

This question already has an answer here:
String Concatenation using '+' operator
(1 answer)
Closed 8 years ago.
tell me pls what's problem with this code C#.
string str = string.Empty;
for (var i = 1; i <= 1000; i++)
str += i.ToString();
This was interview question.
actually there is no problem with your code.
inthis case StringBuilder is more appropriate than string.
because StringBuilder is mutable whereas string is immutable.
so whenever you modify the String object using += it creates a new string object so at the end of your loop it creates many string objects.
but if you use StringBuilder: same object will be modified each time you Append the Strings to it.
You can find more info from MSDN: StringBuilder Class
The String object is immutable. Every time you use one of the methods
in the System.String class, you create a new string object in memory,
which requires a new allocation of space for that new object. In
situations where you need to perform repeated modifications to a
string, the overhead associated with creating a new String object can
be costly. The System.Text.StringBuilder class can be used when you
want to modify a string without creating a new object. For example,
using the StringBuilder class can boost performance when concatenating
many strings together in a loop.
Solution :
This
string str = string.Empty;
for (var i = 1; i <= 1000; i++)
str += i.ToString();
Shouldbe this
StringBuilder str =new StringBuilder();
for (var i = 1; i <= 1000; i++)
str.Append(i.ToString());
There is an answer here.
the compiler can't do anything if you concatenate in a loop and this does generate a lot of garbage.

Categories

Resources