C#C
C#3y ago
Hugh

❔ ✅ 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:
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();


Thanks
Was this page helpful?