📜  c# list join - C# (1)

📅  最后修改于: 2023-12-03 15:29:45.900000             🧑  作者: Mango

C# List Join

In C#, List is a commonly used collection class that represents a strongly typed list of objects that can be accessed by index. Sometimes, we need to concatenate the elements of a List into a single string, and this can be done using the String.Join method.

Syntax

The syntax of String.Join method is:

public static string Join(string separator, IEnumerable<string> values);

Here,

  • separator: A string that is used as a separator between the elements in the resulting string.
  • values: An IEnumerable<string> that contains the strings to concatenate.
Example

Let's consider an example where we want to join a list of strings with a comma separator.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> fruits = new List<string>() { "apple", "banana", "orange", "kiwi" };

        string result = String.Join(",", fruits);

        Console.WriteLine(result);
    }
}

The output of this program would be:

apple,banana,orange,kiwi
Conclusion

The String.Join method is a useful method to join a list of string elements into a single string with a specified separator. It is very easy to use and saves time and effort in writing code to do the same thing.