for each - else extension method

Hi there,

I've implemented nice foreach-else extention method to handle what happens if the loop does not hit. 

public static IEnumerable<TSource> Else<TSource>(this IEnumerable<TSource> source, Action @else)
    bool loopHit = false;
    foreach (var item in source)
        loopHit = true;
        yield return item;
    if ((loopHit == false) && (@else != null))


foreach (KeyValuePair item in GetPairs().Else(()=>Console.WriteLine("No entry!!")))
    Console.WriteLine("{0}: {1}", item.Key, item.Value);



Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at