Skip to content

Instantly share code, notes, and snippets.

@InvertedAcceleration
Last active September 30, 2016 16:26
Show Gist options
  • Save InvertedAcceleration/2150177 to your computer and use it in GitHub Desktop.
Save InvertedAcceleration/2150177 to your computer and use it in GitHub Desktop.
Extension method for IEnumerable
public static class IEnumerableExtensions {
public static IEnumerable<TSource> Alternate<TSource>(this IEnumerable<TSource> self, IEnumerable<TSource> with) {
using (var selfEnumerator = self.GetEnumerator())
using (var withEnumerator = with.GetEnumerator()) {
bool selfHasCurrent;
bool withHasCurrent;
do {
selfHasCurrent = selfEnumerator.MoveNext();
withHasCurrent = withEnumerator.MoveNext();
if (selfHasCurrent) yield return selfEnumerator.Current;
if (withHasCurrent) yield return withEnumerator.Current;
} while (selfHasCurrent || withHasCurrent);
}
}
public static T FirstOrNew<T>(this IEnumerable<T> list, Func<T, bool> predicate) where T : class, new() {
return list.FirstOrDefault(predicate) ?? new T();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment