-
Notifications
You must be signed in to change notification settings - Fork 32
/
Repeat.cs
42 lines (36 loc) · 1.27 KB
/
Repeat.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections.Generic;
namespace Kethane.EnumerableExtensions
{
public static class Repeat
{
public static IEnumerable<T> RepeatFirst<T>(this IEnumerable<T> sequence)
{
if (sequence == null) { throw new ArgumentNullException("sequence"); }
return repeatFirstImpl(sequence, true);
}
public static IEnumerable<T> RepeatFirstOrEmpty<T>(this IEnumerable<T> sequence)
{
if (sequence == null) { throw new ArgumentNullException("sequence"); }
return repeatFirstImpl(sequence, false);
}
private static IEnumerable<T> repeatFirstImpl<T>(IEnumerable<T> sequence, bool throwOnEmpty)
{
using (var enumerator = sequence.GetEnumerator())
{
if (!enumerator.MoveNext())
{
if (throwOnEmpty) { throw new InvalidOperationException("Sequence is empty"); }
yield break;
}
T first = enumerator.Current;
yield return first;
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
yield return first;
}
}
}
}