我有这样的代码:
IEnumerable<string?> items = new [] { "test", null, "this" };
var nonNullItems = items.Where(item => item != null); //inferred as IEnumerable<string?>
var lengths = nonNullItems.Select(item => item.Length); //nullability warning here
Console.WriteLine(lengths.Max());
Run Code Online (Sandbox Code Playgroud)
我如何以一种方便的方式编写此代码,例如:
nonNullItems推断为IEnumerable<string>。item!(因为我想从编译器的健全性检查中受益,而不是依靠我成为无错误的编码器)我知道这种解决方案,它利用了C#8.0编译器中的流敏感型输入,但是它不是很漂亮,主要是因为它又长又嘈杂:
var notNullItems = items.SelectMany(item =>
item != null ? new[] { item } : Array.Empty<string>())
);
Run Code Online (Sandbox Code Playgroud)
有更好的选择吗?