コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】Java の Stream API の Peek のような機能を LINQ で使えるようにする拡張メソッド

ソースコード

using System;
using System.Collections.Generic;
using JetBrains.Annotations;

namespace Kogane
{
    public static class IEnumerablePeekExtensionMethods
    {
        public static IEnumerable<T> Peek<T>
        (
            [NotNull] this IEnumerable<T> source,
            [NotNull]      Action<T>      action
        )
        {
            if ( source == null ) throw new ArgumentNullException( nameof( source ) );
            if ( action == null ) throw new ArgumentNullException( nameof( action ) );

            IEnumerable<T> Iterator()
            {
                foreach ( var x in source )
                {
                    action( x );
                    yield return x;
                }
            }

            return Iterator();
        }

        public static IEnumerable<T> PeekMany<T>
        (
            [NotNull] this IEnumerable<T>         source,
            [NotNull]      Action<IEnumerable<T>> action
        )
        {
            if ( source == null ) throw new ArgumentNullException( nameof( source ) );
            if ( action == null ) throw new ArgumentNullException( nameof( action ) );

            IEnumerable<T> Iterator()
            {
                action( source );

                foreach ( var x in source )
                {
                    yield return x;
                }
            }

            return Iterator();
        }
    }
}

使用例

using System.Linq;
using Kogane;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
        var list1 = Enumerable
                .Range( 0, 3 )
                .Peek( x => Debug.Log( x ) )
                .ToArray()
            ;

        var list2 = Enumerable
                .Range( 0, 3 )
                .PeekMany( x => Debug.Log( string.Join( "\n", x ) ) )
                .ToArray()
            ;
    }
}