227

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
skjcyber
  • 5,759
  • 12
  • 40
  • 60

15 Answers15

421

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.

Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
  • 11
    In .NET 3.5 and below you have to explicitly convert your list to array with `lst.ToArray()`, as there is no direct overload there yet. – Anton Dec 15 '13 at 11:09
84

You can use String.Join method to combine items:

var str = String.Join(",", lst);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
33

Using String.Join:

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

Using LINQ aggregation:

lst .Aggregate((a, x) => a + "," + x);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Muhammad Hani
  • 8,476
  • 5
  • 29
  • 44
  • 1
    I have list of type int32. when I use aggregate function you mentioned, it says "Cannot convert lambda expression to delegate type 'System.Func' because some of the return types in the block are not implicitly convertible to the delegate return type " and "Cannot implicitly convert type 'string' to 'int'" – Hari Jan 14 '15 at 12:31
  • 1
    @Hari You must convert it to string values before you Aggragate to string. So you can do something like this: list.Select(x => string.Format("{0}:{1}", x.Key, x.Value)).Aggregate((a, x) => a+ ", " + x); – bets Jul 20 '17 at 08:14
11

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!

Rejwanul Reja
  • 1,339
  • 1
  • 17
  • 19
  • 2
    This is essentially identical to [the accepted answer from 2013](https://stackoverflow.com/questions/14959824/convert-list-into-comma-separated-string/14959865#14959865). – Peter Mortensen Jun 11 '21 at 01:13
10

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()));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
6

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());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

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

var result= String.Join(",", yourList);
Abdus Salam Azad
  • 5,087
  • 46
  • 35
4
@{ 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

Try

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

HTH

Jay
  • 9,561
  • 7
  • 51
  • 72
1

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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1
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#

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hitesh kumar
  • 69
  • 1
  • 1
0

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()));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
LedgerTech
  • 63
  • 1
  • 8
0
categories = ['sprots', 'news'];
categoriesList = ", ".join(categories)
print(categoriesList)

This is the output: sprots, news

0

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);
Fateme Mirjalili
  • 762
  • 7
  • 16
-1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
satish
  • 1,571
  • 1
  • 11
  • 4