如何将 ReadLine 循环重构为 Linq
How do I refactor a ReadLine loop to 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 移到那里是一个天真的解决方案,但我觉得可能有更好的方法。
基本上,您需要一种从 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");
我想让下面的代码更清晰(在旁观者的眼中)。
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 移到那里是一个天真的解决方案,但我觉得可能有更好的方法。
基本上,您需要一种从 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");