❔ ✅ Best way to just get not null values from a collection of possibly null values
I've got a
List<MyType?>
, and I want to filter out all null values and get a List<MyType
back.
Which of these is preferable (and more idiomatic) for this, or is there a 3rd better way:
Thanks20 Replies
just
should suffice
If I do that,
x
is still a List<MyType?>
, though, even though I know that there aren't any null values in it
And then when I iterate over it later on, my IDE will still want me to check for nullah
okay then
define the type explicitly and cast
So
Cast<MyType>()
over Select(item => item!)
Important distinction, is
MyType
a struct?it's a class
Good point
right
Henkypenky#4865
REPL Result: Success
Console Output
Compile: 711.182ms | Execution: 130.866ms | React with ❌ to remove this embed.
Then you can do what @Henkypenky said will work and you can safely ignore any null warnings.
yeah
Cast is ...
ToList
also allows you to explicitly set the type, .Where(x => x is not null)!.ToList<string>();
would work
with the null forgiveness just thrown in thereas long as you slap a
!
at the end
to signify that you know it's valid and null-safe
that will give you a nullability warning but yeah you can just forgive it so, dunno if I'd bother with the cast as well when ToList allows you to specify the type, but that's up to you
always bump into this, so weird that the static analysis can't detect this with any reliability
it's also a semantics thing right, cause the type is declared as nullable, you just filtered the collection, you know nothing is null, but yeah as Task says the analyzers don't always get it right, they have to cover a lot of basis
just one of those annoying little nullability quirks you learn to live with
indeed
Thanks all - this has been helpful
How about if I didn't specifically want a
List<MyType>
, but just wanted to get an IEnumerable<MyType>
instead?
yeah - it certainly seems that this should be able to be dealt withjust
.Cast<Type>();
without the ToList()
call at all👍
Thanks - appreciate the help here
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.