読者です 読者をやめる 読者になる 読者になる

コレクションの結合(Join)

以前C++で作ったjoinC#で作ってみました

複数のコレクションを結合して、一度のループで全てを走査します



使い方

List<int>       ar  = new List<int>{3, 1, 4};
LinkedList<int> lar = new LinkedList<int>();

lar.AddLast(2);
lar.AddLast(5);
lar.AddLast(6);

foreach (int value in Make.Join(ar, lar))
    Console.WriteLine(value);
3
1
4
2
5
6

ソース(Join.cs)

using System;
using System.Collections.Generic;
using System.Linq;

namespace Shand
{
    public class Jointer<T>
    {
        List<T> _elements;

        public Jointer(IEnumerable<T> elements)
        {
            _elements = new List<T>();
            Add(elements);
        }

        public void Add(IEnumerable<T> elements)
        {
            foreach (T value in elements)
                _elements.Add(value);
        }

        public IEnumerator<T> GetEnumerator()
        {
            foreach (T value in _elements)
                yield return value;
        }
    }

    public static partial class Make
    {
        public static Jointer<T> Join<T>(IEnumerable<T> arg1, IEnumerable<T> arg2)
        {
            Jointer<T> jointer = new Jointer<T>(arg1);
            jointer.Add(arg2);

            return jointer;
        }

        public static Jointer<T> Join<T>(IEnumerable<T> arg1, IEnumerable<T> arg2, IEnumerable<T> arg3)
        {
            Jointer<T> jointer = Join(arg1, arg2);
            jointer.Add(arg3);

            return jointer;
        }

        public static Jointer<T> Join<T>(IEnumerable<T> arg1, IEnumerable<T> arg2, IEnumerable<T> arg3, IEnumerable<T> arg4)
        {
            Jointer<T> jointer = Join(arg1, arg2, arg3);
            jointer.Add(arg4);

            return jointer;
        }

        public static Jointer<T> Join<T>(IEnumerable<T> arg1, IEnumerable<T> arg2, IEnumerable<T> arg3, IEnumerable<T> arg4, IEnumerable<T> arg5)
        {
            Jointer<T> jointer = Join(arg1, arg2, arg3, arg4);
            jointer.Add(arg5);

            return jointer;
        }
    }
}