How to Get a Comma Separated String From an Array in C#?
Last Updated :
17 Jan, 2022
Given an array, now our task is to get a comma-separated string from the given array. So we can do this task using String.Join() method. This method concatenates the items of an array with the help of a comma separator between each item of the array.
Syntax:
String.Join(",", array_name)
Where array_name is the input array.
Example:
Input: {"sireesha", "priyank", "ojaswi", "gnanesh"}
Output: sireesha,priyank,ojaswi,gnanesh
Input: {"sireesha", "priyank"}
Output: sireesha,priyank
Approach 1:
- Declare an array of strings.
- Use the string join() function to get the comma separated strings.
String.Join(",", names)
- Display the final result.
Example:
C#
using System;
class GFG{
public static void Main()
{
String[] names = { "sireesha" , "priyank" ,
"ojaswi" , "gnanesh" };
var str1 = String.Join( "," , names);
Console.WriteLine(str1);
}
}
|
Output:
sireesha,priyank,ojaswi,gnanesh
Approach 2:
We can also find the command-separated string from the object array.
- Create a class named MyEmployee with First_Name and Last_Name methods.
- Declare object array of MyEmployee in the main method.
- Use string join() function to get the comma separated strings.
String.Join(",", e.Select(m => m.First_Name));
Here, we only join the first name so we use the select method to select the First_Name of the employees.
- Display the final result.
Example 2:
C#
using System;
using System.Linq;
class MyEmployee
{
public string First_Name { get ; set ; }
public string Last_Name { get ; set ; }
}
class GFG{
public static void Main()
{
MyEmployee[] e = {
new MyEmployee(){ First_Name = "Sumi" , Last_Name = "Goyal" },
new MyEmployee(){ First_Name = "Mohan" , Last_Name = "Priya" },
new MyEmployee(){ First_Name = "Sumit" , Last_Name = "Singh" }
};
var res = String.Join( "," , e.Select(m => m.First_Name));
Console.WriteLine( "Final String:" + res);
}
}
|
Output:
Final String:Sumi,Mohan,Sumit
Share your thoughts in the comments
Please Login to comment...