Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

What do you think of my own implementation of the extension method SelectMany? Motivating criticism is always welcome.

public static IEnumerable<TResult> MySelectMany<T, TResult>(this IEnumerable<T> source, Func<T, IEnumerable<TResult>> selector)
{
    var theList = new List<TResult>();

    foreach (T item in source)
    {
        foreach (TResult inneritem in selector(item))
        {
            theList.Add(inneritem);
        }
    }

    return theList as IEnumerable<TResult>;
}
share|improve this question
1  
You're doing this just as a learning exercise, right? Otherwise, reimplementing framework code doesn't make much sense. – svick Jul 25 '12 at 10:35
Just to learn indeed. Fooling around with extension methods and delegates etc... :) – HerbalMart Jul 25 '12 at 10:40
2  
For a detailed explanation about how to implement all of LINQ extension methods, see Jon Skeet's series Edulinq. Specifically, part 9 is about SelectMany(). – svick Jul 25 '12 at 11:06
Thanks for that link! – HerbalMart Jul 25 '12 at 11:29

1 Answer

up vote 6 down vote accepted

The as cast in the return statement is entirely redundant, it doesn’t serve a purpose.

Furthermore, The problem with this implementation is that it’s not lazy. You should use a yield generator instead.

public static IEnumerable<TResult> MySelectMany<T, TResult>(this IEnumerable<T> source, Func<T, IEnumerable<TResult>> selector)
{
    foreach (T item in source)
        foreach (TResult inneritem in selector(item))
            yield return inneritem;
}

If C# already had a yield from statement, this would be even shorter since you wouldn’t need to iterate the inner items explicitly.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.