DEV Community

Karen Payne
Karen Payne

Posted on

C# Different way to join string array

Learn how to create a comma delimited string that goes past using String.Join method.

Code blocks

Rather than use separate methods, all code is presented in the main method of a Console project.

{
  code
}
Enter fullscreen mode Exit fullscreen mode

Where code is isolated from all other code.

Note, index = 1; in this case is out of scope from the assignment.

{
    {
        int index = 0;
    }

    index = 1;
}
Enter fullscreen mode Exit fullscreen mode

Convention method to join

Using String.Join to create a comma delimited string of month names which once joined as a string there is no easy method to modify data e.g. add/remove, in this case a month name.

Console.WriteLine(string.Join(",", 
    DateTimeFormatInfo.CurrentInfo.MonthNames[..^1]));
Enter fullscreen mode Exit fullscreen mode

CommaDelimitedStringCollection

CommaDelimitedStringCollection class provides methods and properties to add, edit, test if values exists, iterate with a for statement and much more.

🛑 Downside and one may guess as the name implies, the delimiter can not be changed from a comma.

Create an instance of CommaDelimitedStringCollection and add month names.

CommaDelimitedStringCollection result = new();
result.AddRange(DateTimeFormatInfo.CurrentInfo.MonthNames[..^1]);
Enter fullscreen mode Exit fullscreen mode

Display the results

Console.WriteLine($"\t{result}");
Enter fullscreen mode Exit fullscreen mode

Remove the current month.

var currentMonthName = 
    DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);
result.Remove(currentMonthName);
Enter fullscreen mode Exit fullscreen mode

Insert the current month back in.

result.Insert(DateTime.Now.Month -1, currentMonthName);
Enter fullscreen mode Exit fullscreen mode

What is cool is iterating the collection, in this case month name.

for (var index = 0; index < result.Count; index++)
{
    Console.WriteLine($"{index +1, -3}{result[index]}");
}
Enter fullscreen mode Exit fullscreen mode

Results

1  January
2  February
3  March
4  April
5  May
6  June
7  July
8  August
9  September
10 October
11 November
12 December
Enter fullscreen mode Exit fullscreen mode

Useful for debugging

Example, a developer is testing the following method to find files.

static class FileHelpers
{
    /// <summary>
    /// Find files with no regard to if the user has permissions
    /// </summary>
    /// <param name="path">Folder name to check</param>
    /// <param name="extensions">file extensions</param>
    /// <returns></returns>
    public static string[] FilterFiles(string path, params string[] extensions)
        => extensions
            .Select(filter => $"*.{filter}")
            .SelectMany(item =>
                Directory.EnumerateFiles(
                    path,
                    item,
                    SearchOption.AllDirectories)).ToArray();
}
Enter fullscreen mode Exit fullscreen mode

Rather than using StringBuilder the developer can use CommaDelimitedStringCollection.

{
    AnsiConsole.MarkupLine("[yellow]Files found[/]");
    CommaDelimitedStringCollection result = new();
    var files = FileHelpers.FilterFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory),"txt","json");
    foreach (var file in files)
    {
        result.Add(Path.GetFileName(file));
    }
    Console.WriteLine($"\t{result}");
    Console.WriteLine(result.Contains("appsettings.json").ToYesNo());
}
Enter fullscreen mode Exit fullscreen mode

Using numerics

As the name implies CommaDelimited*StringCollection* there are no overloads for other types but we can simply do a conversion.

For int array, use the following language extension.

static class Extensions
{
    /// <summary>
    /// int array to string array
    /// </summary>
    /// <param name="sender"></param>
    public static string[] ToStringArray(this int[] sender)
        => sender.Select(x => x.ToString()).ToArray();
}
Enter fullscreen mode Exit fullscreen mode

Usage

int[] items = { 1, 2, 3 };
CommaDelimitedStringCollection result = new();
result.AddRange(items.ToStringArray());
Enter fullscreen mode Exit fullscreen mode

Check if 3 is in the collection.

result.Contains("3")
Enter fullscreen mode Exit fullscreen mode

Set to read only

For when the collection should not be modified, use SetReadOnly() method.

{
    AnsiConsole.MarkupLine("[yellow]Files found[/]");
    CommaDelimitedStringCollection result = new();
    var files = FileHelpers.FilterFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory), "txt", "json");
    foreach (var file in files)
    {
        result.Add(Path.GetFileName(file));
    }
    Console.WriteLine($"\t{result}");
    Console.WriteLine(result.Contains("appsettings.json").ToYesNo());

    result.SetReadOnly();
    try
    {
        result.Add("SomeFile.txt");
    }
    catch (Exception e)
    {
        Console.WriteLine(e);

    }
}
Enter fullscreen mode Exit fullscreen mode

Rather than try/catch

result.SetReadOnly();
if (!result.IsReadOnly)
{
    result.Add("SomeFile.txt");
}
Enter fullscreen mode Exit fullscreen mode

screenshot of code samples

Clear the collection

See the Clear method.

Clone the collection

See the Clone method

NuGet packages required

🔸 System.Configuration.ConfigurationManager

Source code

Can be found here which is in a GitHub repository with a mix of other code samples.

Top comments (0)