2011-12-23 56 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(); 
}