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,priyankApproach 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# program to display the comma separated
// string from an array
using System;
class GFG{
public static void Main()
{
// Creating an array of string elements
String[] names = { "sireesha", "priyank",
"ojaswi", "gnanesh" };
// Join the elements separated by comma
// Using Join() method
var str1 = String.Join(",", names);
// Display the final string
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# program to display the comma separated
// string from an array
using System;
using System.Linq;
// MyEmployee class
class MyEmployee
{
public string First_Name { get; set; }
public string Last_Name { get; set; }
}
class GFG{
public static void Main()
{
// Creating object array of MyEmployee
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" }
};
// Join the elements separated by comma
// Using Join() method
var res = String.Join(",", e.Select(m => m.First_Name));
// Display the final result
Console.WriteLine("Final String:" + res);
}
}
Output:
Final String:Sumi,Mohan,Sumit