我的逻辑类似于下面的代码.好像为了检查这样的空引用,我必须有两个单独的Select语句.linq忍者可以告诉我这样的查询可以改进吗?
List<C> cList = Globals.GetReferences(irrelevantThing) // GetReferences returns List<A>, which are references to B
.Select(a => a.GetB()) // GetB returns type B, can be null
.Where(b => b != null && someOtherConditions)
.Select(c => new C(b)) // C Constructor cannot have a null parameter
.ToList();
Run Code Online (Sandbox Code Playgroud)
谢谢.
编辑:稍微清理一下示例代码.
好吧,有一件事我会更改参数名称 - 在第一个之后Select
,你有一个B,所以为什么不调用它b
?
List<B> bList = Globals.GetReferences(irrelevantThing)
.Select(a => a.GetB()) // GetB returns type B, can be null
.Where(b => b != null && someOtherConditions)
.Select(b => new B(b))
.ToList();
Run Code Online (Sandbox Code Playgroud)
那时候,我不得不想知道为什么你会得到第二个Select
......你已经有了B,所以你为什么要创建一个新的?什么是B(B old)
构造函数吗?
如果你确实需要另一个选择,那对我来说似乎没问题.我的意思是,如果GetB
价格便宜,你可以随时使用:
List<B> bList = Globals.GetReferences(irrelevantThing)
.Where(a => a.GetB() != null && someOtherConditions)
.Select(a => new B(a.GetB()))
.ToList();
Run Code Online (Sandbox Code Playgroud)
...但说实话,我不确定.
归档时间: |
|
查看次数: |
166 次 |
最近记录: |