Linq“选择”理智问题
我的逻辑类似于下面的代码。似乎为了检查这样的空引用,我必须有两个单独的 Select 语句。 linq ninja 能告诉我如何改进这样的查询吗?
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();
谢谢。
编辑:稍微清理了示例代码。
I have logic similar to the code below. It seems as though in order to check for null references like this, I have to have two separate Select statements. Could a linq ninja tell me in which way a query like this could be improved?
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();
Thank you.
EDIT: Cleaned up example code a little bit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,首先我会更改参数名称 - 在第一个
Select
之后,您会得到一个 B,那么为什么不将其称为b
呢?那时,我想知道为什么你有第二个
Select
...你已经有了一个 B,那么你为什么要创建一个新的呢?B(B old)
构造函数有什么作用?如果您确实需要其他选择,那对我来说似乎没问题。我的意思是,如果
GetB
很便宜,你总是可以使用:...但说实话,我不确定我会不会。
Well, for one thing I'd change the parameter names - after the first
Select
, you've got a B, so why not call itb
?At that point, I have to wonder why you've got the second
Select
at all... you've already got a B, so why are you creating a new one? What does theB(B old)
constructor do?If you do need the other select though, that seems okay to me. I mean, if
GetB
is cheap, you could always use:... but I'm not sure I would, to be honest.
我发现使用查询语法和
let
运算符看起来稍微更好一些:不过取决于您的偏好...
仅供参考,在扩展方法语法中,上面的内容转换为
更新:刚刚意识到您也可以使用
select into
子句从字面上翻译确切的原始查询:不过仍然更喜欢
let
...I find it slightly better looking with the query syntax and the
let
operator:Depends on your preferences though...
FYI in extension method syntax, the above translates to
UPDATE: just realized that you can also use the
select into
clause to translate the exact original query literally :still prefer
let
though...