-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Where.cs
52 lines (46 loc) · 1.63 KB
/
Where.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
namespace SuperLinq;
public static partial class SuperEnumerable
{
/// <summary>
/// Filters a sequence of values based on an enumeration of boolean values
/// </summary>
/// <typeparam name="TSource">
/// The type of the elements of source.
/// </typeparam>
/// <param name="source">
/// An <see cref="IEnumerable{T}"/> to filter.
/// </param>
/// <param name="filter">
/// An <see cref="IEnumerable{T}"/> of boolean values identifying which elements of <paramref name="source"/> to
/// keep.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that contains elements from the input sequence where the matching value in
/// <paramref name="filter"/> is <see langword="true"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="filter"/> is <see langword="null"/>.
/// </exception>
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, IEnumerable<bool> filter)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(filter);
return Core(source, filter);
static IEnumerable<TSource> Core(IEnumerable<TSource> source, IEnumerable<bool> filter)
{
using var sIter = source.GetEnumerator();
using var fIter = filter.GetEnumerator();
while (true)
{
var sMoved = sIter.MoveNext();
var fMoved = fIter.MoveNext();
if (sMoved != fMoved)
ThrowHelper.ThrowArgumentException(nameof(filter), "'source' and 'filter' did not have equal lengths.");
if (!sMoved)
yield break;
if (fIter.Current)
yield return sIter.Current;
}
}
}
}