Convert a list into a comma-separated string

C#.Net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Enjoy!

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.

Solution 2 - C#

You can use String.Join method to combine items:

var str = String.Join(",", lst);

Solution 3 - C#

Using String.Join:

string.Join<string>(",", lst);

Using LINQ aggregation:

lst .Aggregate((a, x) => a + "," + x);

Solution 4 - C#

If you have a collection of ints:

List<int> customerIds= new List<int>() { 1,2,3,3,4,5,6,7,8,9 };  

You can use string.Join to get a string:

var result = String.Join(",", customerIds);

Enjoy!

Solution 5 - C#

Follow this:

List<string> name = new List<string>();

name.Add("Latif");
name.Add("Ram");
name.Add("Adam");
string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));

Solution 6 - C#

You can refer to the below example for getting a comma-separated string array from a list.

Example:

List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5

string JoinDataString = string.Join(",", testList.ToArray());

Solution 7 - C#

> You can use String.Join for this if you are using .NET framework> 4.0.

var result= String.Join(",", yourList);

Solution 8 - C#

@{ var result = string.Join(",", @user.UserRoles.Select(x => x.Role.RoleName));
    @result
}

I used in MVC Razor View to evaluate and print all roles separated by commas.

Solution 9 - C#

Try

Console.WriteLine((string.Join(",", lst.Select(x=>x.ToString()).ToArray())));

HTH

Solution 10 - C#

We can try like this to separate list entries by a comma:

string stations = 
haul.Routes != null && haul.Routes.Count > 0 ?String.Join(",",haul.Routes.Select(y => 
y.RouteCode).ToList()) : string.Empty;

Solution 11 - C#

static void Main(string[] args) {
    List<string> listStrings = new List<string>() {"C#", "ASP.NET", "SQL Server", "PHP", "Angular"};
    string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
    Console.Write(CommaSeparateString);
    Console.ReadKey();
}

private static string GenerateCommaSeparateStringFromList(List<string> listStrings){return String.Join(",", listStrings);}

Convert a list of string to a comma-separated string in C#

Solution 12 - C#

You can also override ToString() if your list items have more than one string:

public class ListItem
{
    public string string1 { get; set; }

    public string string2 { get; set; }

    public string string3 { get; set; }

    public override string ToString()
    {
        return string.Join(
        ","
        , string1
        , string2
        , string3);
    }
}

To get a CSV string:

ListItem item = new ListItem();
item.string1 = "string1";
item.string2 = "string2";
item.string3 = "string3";

List<ListItem> list = new List<ListItem>();
list.Add(item);

string strinCSV = (string.Join("\n", list.Select(x => x.ToString()).ToArray()));

Solution 13 - C#

categories = ['sprots', 'news'];
categoriesList = ", ".join(categories)
print(categoriesList)

This is the output: sprots, news

Solution 14 - C#

You can separate list entities by a comma like this:

//phones is a list of PhoneModel
var phoneNumbers = phones.Select(m => m.PhoneNumber)    
                    .Aggregate(new StringBuilder(),
                        (current, next) => current.Append(next).Append(" , ")).ToString();

// Remove the trailing comma and space
if (phoneNumbers.Length > 1)
    phoneNumbers = phoneNumbers.Remove(phoneNumbers.Length - 2, 2);

Solution 15 - C#

You can make use of google-collections.jar which has a utility class called Joiner:

String commaSepString = Joiner.on(",").join(lst);

Or you can use the StringUtils class which has a function called join. To make use of StringUtils class, you need to use common-lang3.jar

String commaSepString=StringUtils.join(lst, ',');

For reference, refer this link Convert Collection into Comma Separated String

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionskjcyberView Question on Stackoverflow
Solution 1 - C#Richard DaltonView Answer on Stackoverflow
Solution 2 - C#Sergey BerezovskiyView Answer on Stackoverflow
Solution 3 - C#Muhammad HaniView Answer on Stackoverflow
Solution 4 - C#Rejwanul RejaView Answer on Stackoverflow
Solution 5 - C#Salim Latif WaigaonkarView Answer on Stackoverflow
Solution 6 - C#Gaurang DhandhukiyaView Answer on Stackoverflow
Solution 7 - C#Abdus Salam AzadView Answer on Stackoverflow
Solution 8 - C#Syed Qasim AbbasView Answer on Stackoverflow
Solution 9 - C#JayView Answer on Stackoverflow
Solution 10 - C#Ajeet SinghView Answer on Stackoverflow
Solution 11 - C#hitesh kumarView Answer on Stackoverflow
Solution 12 - C#ACJView Answer on Stackoverflow
Solution 13 - C#sudharsanan rView Answer on Stackoverflow
Solution 14 - C#Fateme MirjaliliView Answer on Stackoverflow
Solution 15 - C#satishView Answer on Stackoverflow