Using .NET 6 I have the following:
List<String> values = new List<String?> { null, "", "value" }
.Where(x => !String.IsNullOrEmpty(x))
.Select(y => y)
.ToList();
But I am getting the warning:
Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'.
I thought that using
.Where(x => !String.IsNullOrEmpty(x))
would solve the problem but it doesn't. How to fix this?
CodePudding user response:
This is one case where you know better, and can assure the compiler the value is not null
via .Select(y => y!)
List<string> values = new List<string?> { null, "", "value" }
.Where(x => !string.IsNullOrEmpty(x))
.Select(y => y!)
.ToList();
Note : .Select(y => y.Value)
is not going to work, as strings are reference types and string?
represents a nullable reference type, not a nullable value type
As mentioned in the comments by @Patrick Artner. You could also use .Cast<string>()
to similar effect, which is essentially just an iterator and regular cast in a generic method, in turn assuring you have the desired result.
List<string> values = new List<string?> { null, "", "value" }
.Where(x => !string.IsNullOrEmpty(x))
.Cast<string>()
.ToList();
And yet another way (albeit it a little harder to reason about) though likely more efficient
List<string> values = new List<string?> { null, "", "value" }
.Where(x => !string.IsNullOrEmpty(x))!
.ToList<string>();
CodePudding user response:
You can use the null-forgiving operator after ToList
without extra Select
:
List<string> values = new List<string?> { null, "", "value" }
.Where(x => !string.IsNullOrEmpty(x))
.ToList()!;