1

I have a StringBuilder and I'm trying to append parameters from multiple lists like this:

var sb = new StringBuilder();
var list1 = new List<string>() { "a", "b", "c" }
var list2 = new List<string>() { "d", "e" }
sb.AppendFormat(" {0}, {1}, {2}, {3}, {4} ", list1, list2);

I get an exception :

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

What I did to make it work is create a temporary list

var temp = new List<string>();
temp.AddRange(list1);
temp.AddRange(list2);
sb.AppendFormat(" {0}, {1} ,{2}  ,{3}  ,{4} ", new List().Add);

Is there a more elegant way to do this ?

2 Answers 2

8

You can do something as simple as this:

var result = string.Join(",", list1.Concat(list2));

You can append this to the string builder like this:

sb.Append(result);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this one:

var sb = new StringBuilder();
var list1 = new List<string>() {"a", "b", "c"};
var list2 = new List<string>() {"d", "e"};
sb.AppendFormat(" {0}, {1}, {2}, {3}, {4} ", list1.Concat(list2).ToArray());
Console.WriteLine(sb.ToString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.