2010-05-24 57 views
0

我想刪除單詞列表中的一些漂亮單詞。如何修改或添加新項目到字符串的通用列表中

public System.String CleanNoiseWord(System.String word) 
{ 
    string key = word; 
    if (word.Length <= 2) 
     key = System.String.Empty; 
    else 
     key = word; 
    //other validation here 
    return key; 
} 

public IList<System.String> Clean(IList<System.String> words) 
{ 
    var oldWords = words; 
    IList<System.String> newWords = new string[oldWords.Count()]; 
    string key; 
    var i = 0; 
    foreach (System.String word in oldWords) 
    { 
     key = this.CleanNoiseWord(word); 
     if (!string.IsNullOrEmpty(key)) 
     { 
      newWords.RemoveAt(i); 
      newWords.Insert(i++, key); 
     } 
    } 
    return newWords.Distinct().ToList(); 
} 

但我不能添加,刪除或插入列表中的任何東西!併發生異常NotSupportedException發生>>集合的大小是固定的。我如何修改或添加新的項目到字符串的通用列表?

+0

聽認爲這需要改寫的人。從一個容易混淆命名的函數返回一個標記值是一種非常糟糕的方式來執行似乎是一個簡單的布爾操作。 – 2010-05-24 13:29:01

回答

2

您的代碼是錯誤的。取而代之的

IList<System.String> newWords = new string[oldWords.Count()]; 

將此

IList<System.String> newWords = new List<String>(); 

你並不需要初始化到一定規模有一個通用的列表。

1

您不能將項目插入到固定大小的列表中,愉快的媒介將創建一個新列表並插入爲「乾淨」。

9

當然LINQ中可以使它好和易於:

return words.Where(p => !string.IsNullOrEmpty(CleanNoiseWord(p)) 
      .Distinct() 
      .ToList(); 

當然,我們可以進一步採取這種一步,內聯函數調用CleanNoiseWord,並大幅簡化您的Clean方法:

public IList<System.String> Clean(IList<System.String> words) 
{ 
    return words.Where(p => !string.IsNullOrEmpty(p) && p.Length > 2) 
       .Distinct() 
       .ToList(); 
} 

如果沒有單詞符合謂詞中的條件,則返回空列表。如果您傳遞了一個非常大的列表,並且想要lazy evaluate itMSDN),那麼從最後刪除ToList() - 這樣,在您將其轉換爲實際列表之前,不會執行列表的實際評估。 (公平地說,here's a blog post關於懶惰(延期)評估的一些陷阱)。

4

我建議你創建一個方法

bool IsNoiseWord(string word) 

,並做到這一點:

words.RemoveAll(IsNoiseWord); 

編輯:這隻會實際列出的工作,否則

return words.Where(x=>!IsNoiseWord(x)).Distinct().ToList() 
+0

+1這似乎是最好的答案,如果他可以使用List而不是IList。 – Amsakanna 2010-05-24 13:18:07

3

前面已經說過,數組是一個固定大小的列表。改用List。

IList<string> newWords = new List<string>(oldWords); 
1

繼邁克的回答,

public bool IsNoise(String word) 
{  
    return (word.Length <= 2) && validation2 && validation3;  
} 

public List<String> Clean(List<String> words) 
{ 
    words.RemoveAll(IsNoise); 
    return words; 
} 
相關問題