group
group

Reputation: 9

Filtering for Non-Nullable Strings in C# Lists

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

Answers (1)

Blindy
Blindy

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 nulls 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

Related Questions