2014-04-01 29 views
1

我剛剛學習C#,所以如果解決方案很明顯,請不要責怪我。將字符串拆分爲獨特的分隔符,再次排序並連接

我有逗號分隔的字符串。我想分割它,從分割數組中刪除重複項,排序結果數組,然後再次連接。

E.g.字符串"3,a,b,3,a,c,s,3,1,2,3,3"結果應該是:"1,2,3,a,b,c,s"

我到目前爲止已經試過是下面的代碼:

static void Main(string[] args) 
{ 
     string myStr = "3,a,b,3,a,c,s,3,1,2,3,3"; 
     string[] temp = myStr.Split(','); 
     string res = ""; 
     List<string> myList = new List<string>(); 

     foreach (var t in temp) 
     { 
      if (myList.Contains(t)==false){ 
       myList.Add(t); 
      } 
     } 

     myList.Sort(); 

     foreach(var t in myList){ 
      res+=t +","; 
     } 
     res = res.Substring(0, res.Length - 1); 

     Console.WriteLine(res); 

} 

但我相信有更多effificent方式..在提醒

感謝。

+0

並順序沒有關係? – Sayse

+0

訂單應發送 – user3333333

回答

7

試試這個單行:

Console.WriteLine(string.Join(",",myStr.Split(',').Distinct().OrderBy(x=>x))); 
+2

哇!我無法相信你在一行中做到這一點!我的代碼15行與1行! – user3333333

相關問題