2012-02-21 76 views
4

我有一個字符串數組。我需要從該陣列中刪除一些項目。但我不知道需要刪除的項目的索引。查找並從c中刪除項目#

我的數組是:string [] arr = {「」,「a」,「b」,「」,「c」,「」,「d」,「」,「e」,「f」, 「」,「」}。

我需要刪除「」項目。即刪除「」我的結果應該是 arr = {「a」,「b」,「c」,「d」,「e」,「f」}

我該怎麼做?

+0

.NET是什麼版本的?在.NET 3.5中引入的一些LINQ擴展方法將是完美的。 – GregL 2012-02-21 10:08:12

+0

這裏有幾個問題和答案。檢查出http://stackoverflow.com/questions/457453/remove-element-of-a-regular-array – 2012-02-21 10:08:52

回答

8
string[] arr = {" ", "a", "b", " ", "c", " ", "d", " ", "e", "f", " ", " "}; 
    arr = arr.Where(s => s != " ").ToArray(); 
6

這將刪除所有條目爲空,空,或者只包含空格:

arr.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray(); 

如果由於某種原因,你只需要在你的榜樣刪除像只用一個空格的條目,你可以修改它像這樣:

arr.Where(s => s != " ").ToArray(); 
2

使用LINQ

using System.Linq; 


string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}. 
arr.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); 

或取決於你如何填寫,你可以前

string[] arr = stringToBeSplit.Split('/', StringSplitOptions.RemoveEmptyEntries); 

然後空項做數組不會把你的字符串數組首先