Linq,流媒体&采集

时间:2011-12-23 09:18:18

标签: c# linq collections stream

我有这个方法返回一个字符串数组:

    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而不是List是否有任何兴趣或好处,因为此方法调用返回字符串数组而不是IEnumerable的ReturnsStringArray

3 个答案:

答案 0 :(得分:3)

当您返回List时,您说“所有处理都已完成,而列表包含结果”。

但是,当您返回IEnumerable时,您说“可能仍需要处理”。

在您的示例中,当您返回IEnumerable时,.Where.Select尚未处理。这被称为“延期执行” 如果用户使用结果3次,则.Where.Select将执行3次。可能会有很多棘手的问题。

我建议在从方法返回值时尽可能经常使用List。除了从List获得的附加功能之外,.NET还有许多需要List的优化,调试支持更好,并且减少了意外副作用的可能性!

答案 1 :(得分:0)

List是IEnumerable的具体实现。不同的是

1)IEnumerable只是一个字符串序列,但List可以通过int索引索引,可以添加到和删除,并在特定索引处插入项目。

2)项目可以按序列迭代,但不允许随机访问。 List是一个特定的随机访问变量大小集合。

答案 2 :(得分:0)

我个人建议您返回string[],因为您不太可能希望添加结果(解除List<string>),但看起来您可能需要顺序访问(IEnumerable<string>不是为了)。是否延迟执行取决于您和情况;如果结果多次使用,在返回结果之前调用ToArray()可能是明智的。

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