【问题标题】:How do I convert List<String?> to List<String> in .NET 6 / C# 10?如何在 .NET 6 / C# 10 中将 List<String?> 转换为 List<String>?
【发布时间】:2021-12-05 21:33:37
【问题描述】:

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

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

但我收到了警告:

'string?[]' 类型的值中的引用类型的可空性与目标类型'string[]' 不匹配。

我认为使用

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

可以解决问题,但不能。如何解决这个问题?

【问题讨论】:

  • .Cast&lt;string&gt;() 会强迫它 - 但可能有更好的方法
  • .Select(y =&gt; y!) ?

标签: c# .net-6.0 c#-10.0


【解决方案1】:

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

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

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

正如@Patrick Artner 在 cmets 中提到的那样。你也可以使用.Cast&lt;string&gt;() 来达到类似的效果,它本质上只是一个泛型方法中的迭代器和常规转换,从而确保你得到想要的结果。

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

【讨论】:

    【解决方案2】:

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

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

    sharplab.io

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      相关资源
      最近更新 更多