I am doing a concatenation c#
where I want the result to be equal to the following:
variable = "null,null"
But I am doing this concatenation in a for
and it looks more or less like this:
string variable = "";
for (int pos= 0; pos < asientos.Length; pos++)
{
if (pos == asientos.Length - 1)
variable += "null";
else
variable += "null" + ",";
}
The if
one that I place in the iteration is so that the ,
(comma) is not added at the end, now the question or rather doubt is, is there a better way to do that validation in that concatenation?, and if there is, what is it? ?
I recommend you to use
String.Join
and thus you avoid creating the cyclefor
and you have a cleaner and easier to maintain code. Here I provide an example:Hi, could you use remove , this way you would remove the last character you don't need:
To implement this I see two options:
Option 1 (classic)
The keys to this implementation are:
System.Text.StringBuilder
to concatenate the string because it is more optimal than concatenating objectsstring
because, being immutable, a memory re-allocation is performed on each concatenationOption 2 (compact)
The keys to this implementation are:
System.Linq.Enumerable.Repeat
to create the "null" array as many times as necessary (.NET >= 4.0 required)string.Join
to generate the final stringThese examples can be seen working in this .NET Fiddle
I really don't know if option 1 could offer more performance but what is clear is that option 2 is much more compact
This could be a solution:
If the variable
asientos
corresponds to aarray
, you should use the methodJoin
of theString
.Example:
Now if you want the value specifically
null
, see that you declare a variable as int and then assign it a string, I would do it like this:Edit your question a bit on the definition of "variable" must be type
String
.I think you can use a
remove()
as @WilfredoP comments orsubstring()
, for example:Another option, which I think no one has mentioned would be:
1) Concatenate all the elements of the array and a comma (except the last element).
2) Outside the loop concatenates the last element left (no comma of course).
The code would look like this: