开发者

C# Is Creating a Dynamic StringBuilder Array Possible?

I am trying to dynamically create a StringBuilder array in C# and I haven't had much luck.

I want to add information to a StringBuilder (sb) based off of a given client digit that will change dynamically depending on how many clients I might have. I might have 2 or I might have 20. The sb will be used to build a report based per client later in my program.

For example I have the following 3 clients:

    Client A = 0 
    Client B = 1
    Client C = 2

If Client A is reporting he has 8 apples I want to add the string "8 apples" to sb[0].

If Client B is reporting he has 3 oranges I want to add the string "3 oranges" to sb[1].

The above is just a simple example of the idea I am trying to accomplish. In reality I am going to be adding a lot of information to the sb.

I have tried the following w开发者_JAVA百科ithout much luck getting them to work they way I expected or wanted.

StringBuilder[] sbFileError = new StringBuilder[clientCount];
List<StringBuilder> sbFileError = new List<StringBuilder>();

Any thoughts? Is it possible to create a StringBuilder array?

Thanks!


You've created the containers above, but you need to fill them with something. For example:

StringBuilder[] sbFileError = new StringBuilder[clientCount];
for (int ix = 0;  ix < clientCount;  ++ix)
    sbFileError[ix] = new StringBuilder();

Or

List<StringBuilder> sbFileError = new List<StringBuilder>();
for (int ix = 0;  ix < clientCount;  ++ix)
    sbFileError.Add(new StringBuilder());


Creating the array is the first step, but this only creates places to store StringBuilders. You haven't actually instantiated any StringBuilders at this point. You'll need to do something like this....

StringBuilder[] sbFileError = new StringBuilder[clientCount];
for (int i = 0; i < sbFileError.Length; i++)
    sbFileError[i] = new StringBuilder();


I think you are missing instantiation of array elements. This code works.

int clientCount = 3;
StringBuilder[] sbFileError = new StringBuilder[clientCount];
for(int i=0; i<clientCount; i++)
{
    sbFileError[i] = new StringBuilder();
}

sbFileError[1].Append("Hello World!");


List<StringBuilder> sbFileError = new List<StringBuilder>();

Looks OK, but you have to fill it:

for (int i = 0; i < numClients; i++)
   sbFileError.Add(new StringBuilder());


You could also get fancy:

var items = Enumerable.Range(0, clientCount)
                      .Select(i => new StringBuilder());

var list = new List<StringBuilder>(items);

or shorten it to:

var list = Enumerable.Range(0, clientCount)
                     .Select(i => new StringBuilder())
                     .ToList();

Just another egg in the basket.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜