追記:2023/7/5
そもそもReadLines()
の戻り値がIEnumerable<string>
だったのに気づいていませんでした・・・。Listだと思い込んでました。
ReadLines().Aggreagate(...)
すればいいですよね(汗)。
便利なはずなのに標準に存在しない機能には、ちゃんと理由がありますね。
この記事は無用の長物となりましたが、拡張メソッドのサンプル程度には役立つかもしれないので、残しておこうと思います。
StreamReaderに対してAggregateしたい!
ふと、「StreamReaderから取得した各行に対して何か処理をしていく関数型のメソッドってないのかな?(全行取得してメモリにため込んで処理するのではないやつ)」と思い、ChatGPT-4に頼んで作ってもらいました。
プロンプト
StreamReaderの拡張メソッド Aggregate( this StreamReader sr, Func func, T initialValue)を定義してください。
次のように使用します。
int countOfLines = sr.Aggregate(0, (acc, line) => ++acc);
StreamReaderExtensions.Aggregateメソッド
できあがったやつです。
using System.IO;
public static class StreamReaderExtensions
{
public static T Aggregate<T>(this StreamReader sr, T initialValue, Func<T, string, T> func)
{
T result = initialValue;
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
result = func(result, line);
}
return result;
}
}
using (StreamReader sr = new StreamReader(filePath))
{
int countOfLines = sr.Aggregate(0, (acc, line) => ++acc);
Console.WriteLine(countOfLines);
}
普通に便利
using (StreamReader sr = new StreamReader(filePath))
{
var sb = sr.Aggregate(
new StringBuilder(),
(acc, line) => line.StartsWith("#")
? acc
: acc.AppendLine(line)
);
Console.WriteLine(sb.ToString());
}
なんかこれ普通に便利なんですが、巷に既に同じようなものが存在している感じでしょうか?
ChatGPTも一発で出してきましたし。
とはいえ、StreamReaderの現在位置を変えちゃうので副作用がありますし、あまり良くないのかも?
ネタとして残しておきます。