2017-08-24 25 views
2

我正在尋找一種「聰明」的方式來連接字符串與分隔符。很明顯,我可以自己編寫這些代碼,所以我想知道是否有一種簡單的方法(LINQ或者其他一些我不知道的方法)來執行此操作。「聰明」的方式來連接字符串?

說我有一組字符串(可以是任何數量的字符串):

string s1 = "a"; 
string s2 = "b"; 
string s3 = "c"; 

而且我想在連接字符串這樣的結果是一樣的東西a, b, c。這很容易,但這裏有一個轉折點:如果任何字符串都是空的,我不需要額外的逗號。

舉例來說,如果這是我的設置:

string s1 = ""; 
string s2 = "b"; 
string s3 = "c"; 

我想要的結果是b, c(或只是c如果兩個s1s2是空的)。

有沒有簡單的方法來做到這一點?

+3

的string.join .........也許在拋出。凡(S => string.isnullorempty(S)!) – pm100

+0

@ pm100聽起來不錯 - 你能用一個例子回答嗎? – derekantrican

回答

1
var list = new List<string>{"a","b","", null}; 
var res = string.Join(", ", list.Where(s => !string.IsNullOrEmpty(s))); 
+0

太棒了!很簡單! (我編輯它來修復你的語法和大小寫) – derekantrican

2

使用string.Join(...)

using System; 
using System.Linq; 
using System.Collections.Generic; 

namespace Rextester 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      string space = " "; 
      string a = "One"; 
      string b = "Two"; 
      string c = "Three"; 
      var filteredList = (new List<string> { space, a, b, c }).Where(x => !string.IsNullOrWhiteSpace(x)); 
      string abc = string.Join(", ", filteredList); 
      Console.WriteLine(abc); //One, Two, Three 
      Console.ReadKey(); 
     } 
    } 
} 
2
string.Join(",", SOME_STRING_COLLECTION.Where(x => !string.IsNullOrWhiteSpace(x)));