-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Enumerable.WhereNotNull() #41363
Comments
Tagging subscribers to this area: @eiriktsarpalis |
Is there any way to remove the public static class Extensions
{
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) => throw null;
} Behavior:
public static class Extensions
{
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) => throw null;
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : struct => throw null;
} I confirmed in a sample app that this syntax is legal and that the nullability feature behaves as expected when it sees calls to these APIs. |
What about just using |
var values = mySequence
.Where(x => x != null)
.OfType<T>();
// or
var values = mySequence
.Where(x => x != null)
.Select(x => x!);
var values = mySequence
.WhereNotNull(); EDIT: So it turns out I shouldn't be reading issues shortly after I've woken up 🙃 |
Dup of #30381 |
The compiler has limitations what it can infer and express with respect to nullability, especially in the context of generics. When using LINQ, it's common to deal with sequences that should not contain
null
values. Unfortunately, there is no easy way to make the type checker aware when they got removed.Consider this:
Since the
Activator.CreateInstance
may return a null value, the compiler correctly warns me that.OrderBy(t => t.Name)
may null-ref. Sadly, inserting.Where(t => t != null)
doesn't fix this because it doesn't change the return type of theWhere()
method. One also has to insert.Select(t => t!)
to tell the type system that the values are now not-null.Proposed API
We can address this problem by introducing a method that explicitly changes the return type:
It also makes the common tasks of excluding
null
values easier.Usage Examples
The text was updated successfully, but these errors were encountered: