2013-05-03 37 views
1

我正在尋找一種方便的方式來刪除空字符串作爲它們的值的列表項目。方便的方法從集合中刪除空字符串

我知道我可以檢查每個字符串,以查看它是否爲空之前加載到列表中。

List<string> items = new List<string>(); 
if (!string.IsNullOrEmpty(someString)) 
{ 
    items.Add(someString); 
} 

但是,這似乎有點麻煩,特別是如果我有很多字符串添加到列表中。

或者,我可以加載的所有字符串無論是空或不:

List<string> items = new List<string>(); 
items.Add("one"); 
items.Add(""); 
items.Add("two") 

然後遍歷列表,如果一個空字符串被發現將其刪除。

foreach (string item in items) 
{ 
    if (string.IsNullOrEmpty(item)) 
    { 
     items.Remove(item); 
    }    
} 

這些是我唯一的兩個選擇,也許Linq有一些東西嗎?

感謝您的任何幫助。

+2

爲什麼在添加之前檢查空字符串會很麻煩?如果你正在創建這個列表,那麼你完全可以控制進入它的內容 - 爲什麼要在事實之後進行過濾? – 2013-05-03 13:21:47

+0

之後刪除空元素的麻煩是'.Remove'強制複製要刪除的元素後面的所有元素,並向下移動一個索引位置。所以,有很多字符串,你最好創建一個沒有這些空元素的新列表。但是,爲什麼不應該留下那些空的元素呢? – JeffRSon 2013-05-03 13:38:38

+0

@ChrisMcAtackney所以,我會得到這樣的事情: if(!string.IsNullOrEmpty(string1)) items.Add(string1); if(!string.IsNullOrEmpty(string2)) items.Add(string2); if(!string.IsNullOrEmpty(string3)) items.Add(string3); 還是有更優美的方式我失蹤? – Baxter 2013-05-03 13:41:26

回答

5

嘗試:

items.RemoveAll(s => string.IsNullOrEmpty(s)); 

,也可以使用where篩選出來:

var noEmptyStrings = items.Where(s => !string.IsNullOrEmpty(s)); 
+3

你甚至可以在這種情況下刪除lambda語法,因爲類型已經匹配:'items.RemoveAll(String.IsNullOrEmpty);' – 2013-05-03 13:22:16

1

進行了擴展,達倫的答案,你可以使用一個擴展方法:

/// <summary> 
    /// Returns the provided collection of strings without any empty strings. 
    /// </summary> 
    /// <param name="items">The collection to filter</param> 
    /// <returns>The collection without any empty strings.</returns> 
    public static IEnumerable<string> RemoveEmpty(this IEnumerable<string> items) 
    { 
     return items.Where(i => !String.IsNullOrEmpty(i)); 
    } 

而且然後用法:

 List<string> items = new List<string>(); 
     items.Add("Foo"); 
     items.Add(""); 
     items.Add("Bar"); 

     var nonEmpty = items.RemoveEmpty(); 
1

在將字符串添加到列表之前檢查字符串總是比從列表中刪除它們或創建一個全新的字符串要麻煩。你試圖避免字符串比較(實際檢查它的空白,執行速度非常快)並將其替換爲列表複製,這會對應用程序的性能產生很大影響。如果您只能在將字符串添加到列表之前檢查字符串 - 請這樣做,並且不要混合。

+1

好點但是如果集合的創建是由不在你控制之下的代碼完成的呢? – 2013-05-03 13:35:15

+0

當然,如果他無法控制將項目添加到列表中,他應該使用上面提出的方法,但請閱讀我的最後一句。另外 - 他說他可以在將字符串添加到列表之前檢查字符串,但不想,因爲它「很麻煩」。 – Tarec 2013-05-03 13:49:36

+0

@Tarec你會使用類似這樣的東西:http://pastebin.com/A5cBraQL還是有更好的方式來檢查之前添加? (我不能讓列表變成一個類變量) – Baxter 2013-05-03 14:11:51