2011-07-16 47 views
1

我想拆分給定的字符串並從該字符串中刪除重複項。就像我有以下字符串:拆分並從字符串中刪除重複項

這是我在堆棧溢出中的第一篇文章,我是非常新的開發人員,對於如何發佈問題我沒有太多想法。

現在我想分割整個字符串與空格,並且新的數組將沒有重複的條目。

我該怎麼做?

回答

8
"This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question." 
    .Split()      // splits using all white space characters as delimiters 
    .Where(x => x != string.Empty) // removes an empty string if present (caused by multiple spaces next to each other) 
    .Distinct()     // removes duplicates 

Distinct()Where()是LINQ擴展方法,所以你必須在你的源文件using System.Linq;

上述代碼將返回IEnumerable<string>的實例。您應該能夠使用此功能執行大多數操作。如果你確實需要一個數組,你可以在語句中附加.ToArray()

+0

反Linq運動問:有沒有簡單的linqless方式? – Bitterblue

+1

它不夠簡單嗎?我不喜歡'System.Linq'中存在擴展方法的事實。它們本身與「語言集成查詢」無關。它們只是針對枚舉類型的一堆擴展方法。 –

3

將數組添加到HashSet<String>中,這將刪除重複項。 here是HashSet的Micorosft文檔..