Question

I am currently building an extension method which processes an IEnumerable<TSource>. For each item in the source collection I need to yield one or two items of the resulting type.

This is my first approach, which fails, since the method is being left on the first return statement, and forgets about its state when the second return statement is being hit.

public static IEnumerable<TResult> DoSomething<TSource>(this IEnumerable<TSource> source)
    where TResult : new()
{
    foreach(item in source)
    {
        if (item.SomeSpecialCondition)
        {
            yield return new TResult();
        }
        yield return new TResult();
    }
}

How would I implement this scenario correctly?

Was it helpful?

Solution

Your solution should work. Here is a full sample program which demonstrates that approach working:

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

namespace Demo
{
    class Program
    {
        void run()
        {
            var test = DuplicateOddNumbers(Enumerable.Range(1, 10));

            foreach (var n in test)
                Console.WriteLine(n);
        }

        public IEnumerable<int> DuplicateOddNumbers(IEnumerable<int> sequence)
        {
            foreach (int n in sequence)
            {
                if ((n & 1) == 1)
                    yield return n;

                yield return n;
            }
        }

        static void Main(string[] args)
        {
            new Program().run();
        }
    }
}

Also, note Dmitry Dovgopoly's comment about using the correct TSource and TResult.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top