2011-12-23 54 views
0

我有這樣的方法,該方法返回一個字符串數組:LINQ中,流媒體和收集

private static string[] ReturnsStringArray() 
    { 
     return new string[] 
     { 
      "The path of the ", 
      "righteous man is beset on all sides", 
      "by the inequities of the selfish and", 
      "the tyranny of evil men. Blessed is", 
      "he who, in the name of charity and", 
      "good will, shepherds the weak through", 
      "the valley of darkness, for he is", 
      "truly his brother's keeper and the", 
      "finder of lost children. And I will ", 
      "strike down upon thee with great", 
      "vengeance and furious anger those", 
      "who attempt to poison and destroy my", 
      "brothers. And you will know my name", 
      "is the Lord when I lay my vengeance", 
      "upon you" 
     }; 
    } 
} 

我希望編寫使用此方法的方法。由於該方法返回一個數組,而不是一個IEnumerable的,有相同的結果寫這篇文章:

private static IEnumerable<string> ParseStringArray() 
    { 
     return ReturnsStringArray() 
      .Where(s => s.StartsWith("r")) 
      .Select(c => c.ToUpper()); 
    } 

這:

private static List<string> ParseStringArray() 
    { 
     return ReturnsStringArray() 
      .Where(s => s.StartsWith("r")) 
      .Select(c => c.ToUpper()) 
      .ToList(); // return a list instead of an IEnumerable. 
    } 

謝謝。

編輯

我的問題是:是否有任何利益或好處的方法ParseStringArray()返回,因爲這種方法的IEnumerable,而不是一個名單打電話ReturnsStringArray返回字符串數組,而不是一個IEnumerable的

+2

什麼問題?你提供的兩個函數都返回相同的結果。 「義人在四面八方」,但大寫。 – NoLifeKing 2011-12-23 09:21:56

回答

3

當您返回List時,您說「所有處理已完成,並且列表包含結果」。

但是,當您返回IEnumerable時,您說「處理可能仍需要完成」。

在您的示例中,當您返回IEnumerable時,.Where.Select尚未處理。這被稱爲「延期執行」。
如果用戶使用結果3次,那麼.Where.Select將執行3次。有很多棘手的問題可以來自這個問題。

我建議在從方法返回值時儘可能經常使用List。除了可以從List獲得的附加功能外,.NET還有很多優化需要List,調試支持更好,並且減少了意外副作用的機會!

0

列表是IEnumerable的具體實現。區別在於

1)IEnumerable僅僅是一個字符串序列,但List可以通過int索引進行索引,可以添加到並從中刪除,並且可以在特定索引處插入項目。

2)項目可以迭代一個序列,但不允許隨機訪問。列表是特定的隨機訪問可變大小集合。

0

我個人建議您退回string[],因爲您不太可能希望添加結果(取消List<string>),但看起來您可能需要順序訪問(不適用於IEnumerable<string>)。你是否推遲執行取決於你和情況;如果結果多次使用,在返回結果之前調用ToArray()可能是明智的。

private static string[] ParseStringArray() 
{ 
    return ReturnsStringArray() 
     .Where(s => s.StartsWith("r")) 
     .Select(c => c.ToUpper()) 
     .ToArray(); 
}