简体   繁体   English

如何转换列表<string?>列出<string>在 .NET 6 / C# 10?</string></string?>

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

Using .NET 6 I have the following:使用 .NET 6 我有以下内容:

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!)这是您更了解的一种情况,并且可以通过.Select(y => y!)向编译器保证该值不是null

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?注意.Select(y => y.Value)不起作用,因为字符串是引用类型string? represents a nullable reference type , not a nullable value type表示可以为空的引用类型,而不是可以为空的值类型

As mentioned in the comments by @Patrick Artner .正如@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.您也可以使用.Cast<string>()来达到类似的效果,它本质上只是泛型方法中的迭代器和常规转换,从而确保您获得所需的结果。

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 :您可以在ToList之后使用容错运算符,而无需额外的Select

List<string> values = new List<string?> { null, "", "value" }
  .Where(x => !string.IsNullOrEmpty(x))
  .ToList()!;

sharplab.io 夏普实验室.io

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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