Reputation: 9
I'm trying to create a list of non-nullable string values by filtering, but I always end up with a list of nullable strings.
var list = new List<string?> {"Cars", "Audi", "", "1920"};
var list2 = list.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); // return type is List<string?>
Can you help me understand why it doesn't return list of non-nullable strings.
Upvotes: 0
Views: 95
Reputation: 67352
The type doesn't lose its nullability just because you decided to add only non-null
items. After all, nothing is stopping you from adding null
s later.
If you want to change its type, either do it when creating the new list (ie, declare the variable explicitly as List<string>
), or tell the compiler that the objects your filter returns are non-null
:
list.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p!).ToList();
Upvotes: 2