Dot-Net

String.Join 忽略空字元串的方法?

  • May 1, 2013

VB.NET 的方法String.Join(separator, stringArray)類似於 PHP 的 implode,但數組中的任何 null 元素都替換為空字元串,因此:

Dim myArray() as String = { "a", null, "c" }
Console.WriteLine(String.Join(", ", myArray));
// Prints "a, , c"

有沒有一種簡單的方法可以將一組字元串與忽略空字元串的分隔符連接起來?

我不一定需要使用數組或 String.Join 或其他任何東西。我只需要以下轉換:

("a", "b", "c") --> "a, b, c"
("a", null, "c") --> "a, c"

VB.NET

String.Join(",", myArray.Where(Function(s) Not String.IsNullOrEmpty(s)))

C#

String.Join(",", myArray.Where(s => !string.IsNullOrEmpty(s)))

引用自:https://stackoverflow.com/questions/16325995