简体   繁体   中英

How do I convert List<String?> to List<String> in .NET 6 / C# 10?

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?

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>();  

You can fix it like this:

.Where(x => x.HasValue).Select(y => y.Value)

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()!;

sharplab.io

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM