Reputation: 151
I am creating an application in window application using c#. I have a string array,and its value will be updated in each timer tick event. later on ,i have to convert this array into object array. I know, if we are modifying string many times,it can be time consuming to create new string objects.so i want to use stringBuilder.
let say, in timer tick event:
for (int i = 0; i < 10; i++)
{
n[i] = i.ToString();
}
where n is the string array and i want to use stringbuilder instead of array. is it possible? how do i do this? how do i convert stringBuilder type to object type?
Upvotes: 1
Views: 9835
Reputation: 1150
I would suggest you to use code something like :
class Program
{
static void Main(string[] args)
{
var dic = new Dictionary<int, StringBuilder>();
//Initialize dictionary
for (int i = 0; i < 10; i++)
{
dic.Add(i, new StringBuilder());
}
TimerElapsed(dic);
TimerElapsed(dic);
Process(dic.Values.ToArray());
}
public static void Process(object[] objects)
{
//Do your processing
}
public static void TimerElapsed(IDictionary<int, StringBuilder> dic)
{
for (int i = 0; i < 10; i++)
{
dic[i].Append(i.ToString());
}
}
}
Such code will give you benefits of collection and flexibility (for eg: you could convert to array easily)
Upvotes: 0
Reputation: 460138
Here is another approach that does not need to use an array or StringBuilder
and which should be efficient enough if the sequence is not too large:
string nums = String.Join("", Enumerable.Range(0, 10));
However, string.Join
is really efficient if the input is already an array. In this case it might really be more efficient to use a StringBuilder
:
string nums = Enumerable.Range(0, 10)
.Aggregate(new StringBuilder(), (a, b) => a.Append(b))
.ToString();
Upvotes: 0
Reputation: 44439
You can keep your array of strings and use a StringBuilder
in the loop.
var myValues = new String[100];
void tick() {
var sb = new StringBuilder();
for (int i = 0; i < 10; i++){
sb.append(i.ToString());
}
myValues.add(sb.ToString());
}
This adds all values in the range of 0 to 10 to one string. I don't know why you'd need this, so if you want to do something different you should clarify.
Upvotes: 1
Reputation: 273264
You do not need a StringBuilder
here. A StringBuilder is only called for when processing (usually: concatenating) a single string many times. You have many small and unrelated strings.
What you probably want is to replace the array string[]
with a List<string>
.
Upvotes: 2
Reputation: 1075
You can do something like this
StringBuilder obj=new StringBuilder();
for (int i = 0; i < 10; i++)
{
obj.append(i.ToString());
}
Upvotes: 0