diff --git a/CHANGELOG.md b/CHANGELOG.md index 6291042..5fcd310 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ - X10D: Added `IEnumerable.LastWhereNot(Func)` - X10D: Added `IEnumerable.LastWhereNotOrDefault(Func)` - X10D: Added `IEnumerable.WhereNot(Func)` +- X10D: Added `IEnumerable.WhereNotNull()` - X10D: Added `IList.RemoveRange(Range)` - X10D: Added `IList.Swap(IList)` (#62) - X10D: Added `IReadOnlyList.IndexOf(T[, int[, int]])` diff --git a/X10D.Tests/src/Collections/EnumerableTests.cs b/X10D.Tests/src/Collections/EnumerableTests.cs index 1631040..c223c5b 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.cs @@ -287,6 +287,27 @@ public class EnumerableTests Assert.ThrowsException(() => ((IEnumerable?)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; } diff --git a/X10D/src/Collections/EnumerableExtensions.cs b/X10D/src/Collections/EnumerableExtensions.cs index 93e1b67..4a2580a 100644 --- a/X10D/src/Collections/EnumerableExtensions.cs +++ b/X10D/src/Collections/EnumerableExtensions.cs @@ -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)); } + + /// + /// Filters a sequence of values by omitting elements that are ( in + /// Visual Basic). + /// + /// An to filter. + /// The type of the elements of . + /// + /// An that contains elements from the input sequence that are not + /// ( in Visual Basic). + /// + public static IEnumerable WhereNotNull(this IEnumerable 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!); + } }