In previous article, I have mentioned How to add a item or multiple items in C# List and Multiple ways to add newline into a String in C# but now in this article, I have mentioned how to convert list to comma-seperated string using C# or list to new-line seperated string using C# with console application examples.
Convert a list into a comma-separated string using C#
Let's take a look on an example to convert list into comma-seperated string using Console Application in C#.
So, in this article, first we will create a list of string and then we will seperate them to create single string, which has list values seperated by comma.
using System;
using System.Collections.Generic;
public class ListToString
{
public static void Main()
{
// List initialization and adding elements
List<string> lstString = new List<string> { "Hello", "World", "Here" };
var str = String.Join(",", lstString);
Console.WriteLine(str);
// List initialization and adding elements of int
List<int> intString = new List<int> { 9, 7, 6 };
var str2 = String.Join(",", intString);
Console.WriteLine(str2);
}
}
In the above code, we have to 2 list's one of string
type and another is of int
type.
Using String.Join()
method, we are joining list items into string and using "," as delimiter.
Executing above code, gives output as below
Hello,World,Here
9,7,6
Using Linq
You can also use Linq method to convert the list into a comma-separated string.
using System;
using System.Collections.Generic;
using System.Linq;
public class ListToString
{
public static void Main()
{
// List initialization and adding elements
List<string> lstString = new List<string> { "Hello", "World", "Here" };
var str = lstString.Aggregate((a, x) => a + "," + x);
Console.WriteLine(str);
}
}
The output would be the same as above
Hello,World,Here
List to string separated by new-line
Now, we can use NewLine to separate list items instead of using "," comma.
So here is an example of it
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> list = new List<string>()
{
"Red",
"Blue",
"Green"
};
string output = string.Join(Environment.NewLine, list);
Console.Write(output);
}
}
Output:
Red
Blue
Green
That's it, hope it helps.
You may also like to read:
How can I convert string to time in C#?
File I/O in C# (Read, Write, Delete, Copy file using C#)
Object Oriented Programming (OOPS) concepts in c# with example
Converting String to Enum OR Enum to String in C#