1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-09 23:45:42 +00:00

Add IEnumerable<T?>.WhereNotNull()

This commit is contained in:
Oliver Booth 2023-02-27 21:11:37 +00:00
parent 7a6dbef4f9
commit 041181cc5a
No known key found for this signature in database
GPG Key ID: 20BEB9DC87961025
3 changed files with 47 additions and 1 deletions

View File

@ -22,6 +22,7 @@
- X10D: Added `IEnumerable<T>.LastWhereNot(Func<T, bool>)`
- X10D: Added `IEnumerable<T>.LastWhereNotOrDefault(Func<T, bool>)`
- X10D: Added `IEnumerable<T>.WhereNot(Func<T, bool>)`
- X10D: Added `IEnumerable<T>.WhereNotNull()`
- X10D: Added `IList<T>.RemoveRange(Range)`
- X10D: Added `IList<T>.Swap(IList<T>)` (#62)
- X10D: Added `IReadOnlyList<T>.IndexOf(T[, int[, int]])`

View File

@ -287,6 +287,27 @@ public class EnumerableTests
Assert.ThrowsException<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.WhereNot(x => x % 2 == 0));
}
[TestMethod]
public void WhereNotNull_ShouldContainNoNullElements()
{
object?[] array = Enumerable.Repeat(new object(), 10).ToArray();
array[1] = null;
array[2] = null;
array[8] = null;
array[9] = null;
const int expectedCount = 6;
var actualCount = 0;
foreach (object o in array.WhereNotNull())
{
Assert.IsNotNull(o);
actualCount++;
}
Assert.AreEqual(expectedCount, actualCount);
}
private class DummyClass
{
public int Value { get; set; }

View File

@ -1,4 +1,4 @@
using System.Diagnostics.Contracts;
using System.Diagnostics.Contracts;
namespace X10D.Collections;
@ -352,4 +352,28 @@ public static class EnumerableExtensions
return source.Where(item => !predicate(item));
}
/// <summary>
/// Filters a sequence of values by omitting elements that are <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </summary>
/// <param name="source">An <see cref="IEnumerable{T}" /> to filter.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <returns>
/// An <see cref="IEnumerable{T}" /> that contains elements from the input sequence that are not <see langword="null" />
/// (<see langword="Nothing" /> in Visual Basic).
/// </returns>
public static IEnumerable<TSource> WhereNotNull<TSource>(this IEnumerable<TSource?> source)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(source);
#else
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
#endif
return source.Where(item => item is not null).Select(item => item!);
}
}