-
Notifications
You must be signed in to change notification settings - Fork 707
/
EnumerableExtensions.cs
69 lines (61 loc) · 1.88 KB
/
EnumerableExtensions.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
namespace ApiVersioning.Examples;
using System.Collections;
/// <summary>
/// Provides extension methods for the <see cref="IEnumerable"/> interface.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Returns the first element from the specified sequence.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable">sequence</see> to take an element from.</param>
/// <returns>The first element in the sequence or <c>null</c>.</returns>
public static object FirstOrDefault( this IEnumerable enumerable )
{
var iterator = enumerable.GetEnumerator();
try
{
if ( iterator.MoveNext() )
{
return iterator.Current;
}
}
finally
{
if ( iterator is IDisposable disposable )
{
disposable.Dispose();
}
}
return default;
}
/// <summary>
/// Returns a single element from the specified sequence.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable">sequence</see> to take an element from.</param>
/// <returns>The single element in the sequence or <c>null</c>.</returns>
public static object SingleOrDefault( this IEnumerable enumerable )
{
var iterator = enumerable.GetEnumerator();
var result = default( object );
try
{
if ( iterator.MoveNext() )
{
result = iterator.Current;
if ( iterator.MoveNext() )
{
throw new InvalidOperationException( "The sequence contains more than one element." );
}
}
}
finally
{
if ( iterator is IDisposable disposable )
{
disposable.Dispose();
}
}
return result;
}
}