user911671
user911671

Reputation:

How to append my list elements

I have a following string list

          List<string> myList=new List<string>();
           myList.Add("A");
           myList.Add("B");
           myList.Add("C");
           myList.Add("D");
           myList.Add("E");
           myList.Add("F");
           myList.Add("G");
           myList.Add("H");

           string Res=""
           foreach(String str in myList)
           {
               Res+=","+str;
            }

Is there any better method to join my List values than this ??

Thank you All

Upvotes: 1

Views: 553

Answers (3)

Rohit
Rohit

Reputation: 10286

Here is a sample code to do this with String.Join() method

   string delimeter = ",";

        List<string> str = new List<string>();
        str.Add("a");
        str.Add("b");
        str.Add("c");
        str.Add("d");

        string result= String.Join(delimeter, str);

also you could do it with Linq

      string output= str.Aggregate((i, j) => i + delimeter + j);

Upvotes: 3

Mathew Collins
Mathew Collins

Reputation: 376

You can use String.Join if you just want to concatenate them all together, or a StringBuilder if you're also planning on adding other text to it.

String.Join(", ", myList)

Upvotes: 1

David Pilkington
David Pilkington

Reputation: 13618

String.Join is what you are looking for

Have a look here at the MSDN documentation

String.Join Method (String, String[])

string Res = String.Join("," , myList);

Upvotes: 6

Related Questions