1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

StreamReaderに対してAggregateする拡張メソッドを作る

Last updated at Posted at 2023-07-04

追記: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の現在位置を変えちゃうので副作用がありますし、あまり良くないのかも?

ネタとして残しておきます。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?