您可以使用迭代器块轻松编写基于LINQ的行读取器:
static IEnumerable<SomeType> ReadFrom(string file) {
string line;
using(var reader = File.OpenText(file)) {
while((line = reader.ReadLine()) != null) {
SomeType newRecord = /* parse line */
yield return newRecord;
}
}
}
或让乔恩开心:
static IEnumerable<string> ReadFrom(string file) {
string line;
using(var reader = File.OpenText(file)) {
while((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
...
var typedSequence = from line in ReadFrom(path)
let record = ParseLine(line)
where record.Active // for example
select record.Key;
那么您将ReadFrom(...)
获得一个无缓冲的懒惰评估序列,非常适合Where
等。
请注意,如果使用OrderBy
或standard GroupBy
,它将必须在内存中缓冲数据;如果需要分组和聚合,则“ PushLINQ”具有一些精美的代码,可让您对数据执行聚合但将其丢弃(不进行缓冲)。乔恩的解释在这里。