mirror of
https://github.com/oliverbooth/X10D
synced 2024-11-23 01:28:48 +00:00
Add IEnumerable<T?>.WhereNotNull()
This commit is contained in:
parent
7a6dbef4f9
commit
041181cc5a
@ -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]])`
|
||||
|
@ -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; }
|
||||
|
@ -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!);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user