Monday 26 December 2022

Convert a list into a comma-separated string

 Problem:

My code is as below:

public void ReadListItem()
{
     List<uint> lst = new List<uint>() { 1, 2, 3, 4, 5 };
     string str = string.Empty;
     foreach (var item in lst)
         str = str + item + ",";

     str = str.Remove(str.Length - 1);
     Console.WriteLine(str);
}

Output: 1,2,3,4,5

What is the most simple way to convert the List<uint> into a comma-separated string?



-------------------------------------------------------------------------------------------------------

Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));

First Parameter: ","
Second Parameter: new List<uint> { 1, 2, 3, 4, 5 })

String.Join will take a list as a the second parameter and join all of the elements using the string passed as the first parameter into one single string.



No comments:

Post a Comment