📌  相关文章
📜  如何从 C# 中的数组中获取逗号分隔的字符串?

📅  最后修改于: 2022-05-13 01:54:56.740000             🧑  作者: Mango

如何从 C# 中的数组中获取逗号分隔的字符串?

给定一个数组,现在我们的任务是从给定数组中获取一个逗号分隔的字符串。所以我们可以使用 String.Join() 方法来完成这个任务。此方法借助数组的每个项之间的逗号分隔符连接数组的项。

句法:

String.Join(",", array_name)

其中 array_name 是输入数组。

例子:

Input: {"sireesha", "priyank", "ojaswi", "gnanesh"}
Output: sireesha,priyank,ojaswi,gnanesh

Input: {"sireesha", "priyank"}
Output: sireesha,priyank

方法一:

  • 声明一个字符串数组。
  • 使用字符串join()函数获取逗号分隔的字符串。
String.Join(",", names)
  • 显示最终结果。

例子:

C#
// 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);
}
}


C#
// 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);
}
}



输出:

sireesha,priyank,ojaswi,gnanesh

方法二:

我们还可以从对象数组中找到命令分隔的字符串。

  • 使用 First_Name 和 Last_Name 方法创建一个名为 MyEmployee 的类。
  • 在 main 方法中声明 MyEmployee 的对象数组。
  • 使用字符串join()函数获取逗号分隔的字符串。
String.Join(",", e.Select(m => m.First_Name));

在这里,我们只加入了名字,所以我们使用 select 方法来选择员工的 First_Name。

  • 显示最终结果。

示例 2:

C#

// 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);
}
}

输出:

Final String:Sumi,Mohan,Sumit