如何将ReadLine循环重构为Linq

时间:2015-02-06 12:18:05

标签: c# linq

我想让下面的代码更清晰(在旁观者的眼中)。

var lines = new StringReader(lotsOfIncomingLinesWithNewLineCharacters);
var resultingLines = new List<string>();

string line;
while( (line = lines.ReadLine() ) != null )
{
    if( line.Substring(0,5) == "value" )
    {
        resultingLines.Add(line);
    }
}

类似

var resultingLinesQuery = 
    lotsOfIncomingLinesWithNewLineCharacters
    .Where(s=>s.Substring(0,5) == "value );

希望我已经说明我更喜欢没有结果作为列表(不填充内存)并且StringReader不是必需的。

有一个天真的解决方案来创建一个扩展并在那里移动ReadLine但我觉得可能有更好的方法。

1 个答案:

答案 0 :(得分:11)

基本上你需要一种从TextReader中提取线条的方法。这是一个简单的解决方案,只会迭代一次:

public static IEnumerable<string> ReadLines(this TextReader reader)
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        yield return line;
    }
}

您可以将其用于:

var resultingLinesQuery = 
    new StringReader(lotsOfIncomingLinesWithNewLineCharacters)
    .ReadLines()
    .Where(s => s.Substring(0,5) == "value");

但理想情况下,您应该能够多次迭代IEnumerable<T>。如果你只需要这个字符串,你可以使用:

public static IEnumerable<string> SplitIntoLines(this string text)
{
    using (var reader = new StringReader(text))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

然后:

var resultingLinesQuery = 
    lotsOfIncomingLinesWithNewLineCharacters
    .SplitIntoLines()
    .Where(s => s.Substring(0,5) == "value");
相关问题