簡體   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