string.join
csharp
empty strings
method
programming

String.Join method that ignores empty strings?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

String.Join in C# does not skip empty or null strings by default — it includes them, producing doubled delimiters. To ignore empty strings, filter the input collection with LINQ's Where clause before passing it to String.Join. Use string.IsNullOrEmpty() to exclude empty strings, or string.IsNullOrWhiteSpace() to also exclude whitespace-only strings.

The Problem

csharp
1string[] parts = { "Alice", "", "Bob", null, "Charlie", "" };
2
3string result = string.Join(", ", parts);
4Console.WriteLine(result);
5// Output: Alice, , Bob, , Charlie,
6// Empty and null entries produce extra commas

The doubled commas look wrong in display text, CSV output, file paths, and addresses.

Fix: Filter with LINQ

csharp
1using System.Linq;
2
3string[] parts = { "Alice", "", "Bob", null, "Charlie", "  " };
4
5// Remove null and empty strings
6string result = string.Join(", ", parts.Where(s => !string.IsNullOrEmpty(s)));
7Console.WriteLine(result);
8// Output: Alice, Bob, Charlie,
9// Note: "  " (whitespace) is still included
10
11// Remove null, empty, AND whitespace-only strings
12result = string.Join(", ", parts.Where(s => !string.IsNullOrWhiteSpace(s)));
13Console.WriteLine(result);
14// Output: Alice, Bob, Charlie

Extension Method

Create a reusable extension for this common pattern:

csharp
1public static class StringExtensions
2{
3    public static string JoinNonEmpty(this IEnumerable<string> values, string separator)
4    {
5        return string.Join(separator, values.Where(s => !string.IsNullOrWhiteSpace(s)));
6    }
7}
8
9// Usage
10string[] parts = { "Alice", "", "Bob", null, "Charlie" };
11string result = parts.JoinNonEmpty(", ");
12// Output: Alice, Bob, Charlie

Static Helper Method

If you prefer a static method matching String.Join's signature:

csharp
1public static class StringHelper
2{
3    public static string JoinIgnoreEmpty(string separator, params string[] values)
4    {
5        return string.Join(separator, values.Where(s => !string.IsNullOrWhiteSpace(s)));
6    }
7
8    public static string JoinIgnoreEmpty(string separator, IEnumerable<string> values)
9    {
10        return string.Join(separator, values.Where(s => !string.IsNullOrWhiteSpace(s)));
11    }
12}
13
14// Usage
15string result = StringHelper.JoinIgnoreEmpty(", ", "Alice", "", "Bob", null, "Charlie");
16// Output: Alice, Bob, Charlie

Building Addresses

A common use case — joining address parts where some fields may be empty:

csharp
1string street = "123 Main St";
2string apt = "";       // No apartment
3string city = "Springfield";
4string state = "IL";
5string zip = "62704";
6string country = "";   // Domestic, no country
7
8string address = string.Join(", ",
9    new[] { street, apt, city, state + " " + zip, country }
10    .Where(s => !string.IsNullOrWhiteSpace(s))
11);
12Console.WriteLine(address);
13// Output: 123 Main St, Springfield, IL 62704

Building File Paths

csharp
1string basePath = "C:\\Users";
2string subfolder = "";  // May be empty
3string filename = "report.pdf";
4
5// string.Join with Path.DirectorySeparatorChar
6string path = string.Join(
7    Path.DirectorySeparatorChar.ToString(),
8    new[] { basePath, subfolder, filename }
9    .Where(s => !string.IsNullOrWhiteSpace(s))
10);
11Console.WriteLine(path);
12// Output: C:\Users\report.pdf (no double backslash)

For file paths, Path.Combine is preferred over String.Join since it handles separators automatically.

Building SQL or CSV

csharp
1// CSV row — skip empty columns
2string[] columns = { "Alice", "30", "", "[email protected]", null };
3string csvRow = string.Join(",", columns.Where(s => s != null).Select(s => s));
4// Output: Alice,30,,[email protected] — preserves empty for column alignment
5
6// OR skip empty entirely (fewer columns)
7string compactRow = string.Join(",", columns.Where(s => !string.IsNullOrEmpty(s)));
8// Output: Alice,30,[email protected]

For CSV, you usually want to preserve empty strings to maintain column alignment. Only filter when column order does not matter.

IsNullOrEmpty vs IsNullOrWhiteSpace

csharp
1string[] test = { "hello", "", "  ", "\t", null, "world" };
2
3// IsNullOrEmpty: filters null and ""
4var nonEmpty = test.Where(s => !string.IsNullOrEmpty(s)).ToArray();
5// ["hello", "  ", "\t", "world"]
6
7// IsNullOrWhiteSpace: filters null, "", spaces, tabs, newlines
8var nonWhitespace = test.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
9// ["hello", "world"]
InputIsNullOrEmptyIsNullOrWhiteSpace
nulltruetrue
""truetrue
" "falsetrue
"\t\n"falsetrue
"text"falsefalse

Common Pitfalls

  • Forgetting to filter before joining: String.Join includes all elements by default. Without a Where clause, null values become empty strings in the output, producing doubled delimiters.
  • Using IsNullOrEmpty when whitespace should be excluded: Strings containing only spaces or tabs pass the IsNullOrEmpty check. Use IsNullOrWhiteSpace to filter those as well.
  • Filtering in CSV output: Removing empty strings from CSV rows shifts column positions. Only filter when column alignment does not matter, or use a proper CSV library that handles quoting and empty fields.
  • Trimming strings after joining: Calling .Trim() on the joined result removes leading/trailing whitespace from the whole string, not from individual parts. Trim each part before joining: .Select(s => s?.Trim()).
  • Performance with large collections: LINQ's Where creates an iterator that is lazily evaluated. For very large collections, this is efficient because it does not allocate an intermediate array. However, calling .ToArray() before String.Join forces a full allocation — let String.Join consume the IEnumerable directly.

Summary

  • String.Join does not skip empty or null strings — filter with LINQ first
  • Use .Where(s => !string.IsNullOrEmpty(s)) to exclude null and empty strings
  • Use .Where(s => !string.IsNullOrWhiteSpace(s)) to also exclude whitespace-only strings
  • Create an extension method (JoinNonEmpty) for this common pattern
  • For CSV output, consider whether removing empty strings breaks column alignment
  • Pass the filtered IEnumerable directly to String.Join — no need for .ToArray()

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.