加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Linq“选择”理智问题

发布时间:2020-12-16 01:43:33 所属栏目:百科 来源:网络整理
导读:我的逻辑类似于下面的代码.好像为了检查这样的空引用,我必须有两个单独的Select语句. linq忍者可以告诉我这样的查询可以改进吗? ListC cList = Globals.GetReferences(irrelevantThing) // GetReferences returns ListA,which are references to B .Select(
我的逻辑类似于下面的代码.好像为了检查这样的空引用,我必须有两个单独的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();

谢谢.

编辑:稍微清理一下示例代码.

解决方法

我发现使用查询语法和let运算符看起来稍微好一些:

var queryB = from a in Globals.GetReferences(irrelevantThing)
                let b = a.GetB()
                where b != null && someOtherConditions
                select new B(b);

   var bList = queryB.ToList()

取决于你的喜好…

FYI在扩展方法语法中,上面转换为

var queryB = Globals.GetReferences(irrelevantThing)
            .Select(a => new { a,b = a.GetB() })
            .Where(x => x.b != null && someOtherConditions)
            .Select(x => new B(x.b))
            .ToList();

更新:刚才意识到你也可以使用select into子句从字面上翻译确切的原始查询:

var queryB = from a in Globals.GetReferences(irrelevantThing)
                select a.GetB() into b
                where b != null && someOtherConditions
                select new B(b);

仍然喜欢让…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读