I have a list of integers and I want to be able to convert this to a string where each number is separated by a comma.
So far example if my list was:
1 2 3 4 5
My expected output would be:
1, 2, 3, 4, 5
Is this possible using LINQ?
Thanks
A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);
Approach: This can be achieved with the help of join() method of String as follows. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ', ' and the list as parameters. Print the String.
How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].
In C#, Join() is a string method. This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. This method can be overloaded by passing different parameters to it.
In .NET 2/3
var csv = string.Join( ", ", list.Select( i => i.ToString() ).ToArray() );
or (in .NET 4.0)
var csv = string.Join( ", ", list );
Is this what you’re looking for?
// Can be int[], List<int>, IEnumerable<int>, ... int[] myIntegerList = ...; string myCSV = string.Join(", ", myIntegerList.Select(i => i.ToString()).ToArray());
Starting with C# 4.0, the extra mumbojumbo is no longer necessary, it all works automatically:
// Can be int[], List<int>, IEnumerable<int>, ... int[] myIntegerList = ...; string myCSV = string.Join(", ", myIntegerList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With