❔ ✅ Best way to just get not null values from a collection of possibly null values
I've got a
List<MyType?>
List<MyType?>
, and I want to filter out all null values and get a
List<MyType
List<MyType
back.
Which of these is preferable (and more idiomatic) for this, or is there a 3rd better way:
List<MyType> validTypes = possiblyNullTypes.Where(item => item is not null).Cast<MyType>().ToList();List<MyType> validTypes = possiblyNullTypes.Where(item => item is not null).Select(item => item!).ToList();
List<MyType> validTypes = possiblyNullTypes.Where(item => item is not null).Cast<MyType>().ToList();List<MyType> validTypes = possiblyNullTypes.Where(item => item is not null).Select(item => item!).ToList();