繁体   English   中英

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

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

使用 .NET 6 我有以下内容:

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

但我收到警告:

Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'.

我以为使用

.Where(x => !String.IsNullOrEmpty(x))

会解决问题,但它没有。 如何解决这个问题?

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

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

注意.Select(y => y.Value)不起作用,因为字符串是引用类型string? 表示可以为空的引用类型,而不是可以为空的值类型

正如@Patrick Artner在评论中提到的那样。 您也可以使用.Cast<string>()来达到类似的效果,它本质上只是泛型方法中的迭代器和常规转换,从而确保您获得所需的结果。

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

还有另一种方式(尽管它更难推理)虽然可能更有效

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

你可以像这样修复它:

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

您可以在ToList之后使用容错运算符,而无需额外的Select

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

夏普实验室.io

暂无
暂无

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

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