如何最好地组合这两个 LINQ 表达式?
第一个表达式使用另一个标识值检索联系人的 ID。第二个表达式使用联系人 ID 检索整个联系人。看起来我应该能够将这两个陈述合并为一个,但我太挣扎了(累、压力大、犯愚蠢的错误等)。这两个语句有效,我得到了我需要的结果,但我觉得它可以更清晰,并且可能是单个表达式。
感谢大家的帮助!
var contactId = DAL.dc.ContactMrns.Where(cm => cm.MRN == recipient.MRN)
.Select(x => x.ContactId)
.First();
var contact = DAL.dc.Contacts.Where(c => c.ContactID == contactId).First();
The first expression retrieves a contact's ID using another identifying value. The second expression retrieves the whole contact using a contact ID. It seems like I should be able to merge these two statements into one but I'm struggling too much (tired, stressed, making dumb mistakes, etc.). The two statements work and I get the result I need but I feel it could be cleaner and probably a single expression.
Thanks for everyone's help!
var contactId = DAL.dc.ContactMrns.Where(cm => cm.MRN == recipient.MRN)
.Select(x => x.ContactId)
.First();
var contact = DAL.dc.Contacts.Where(c => c.ContactID == contactId).First();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,看起来这可能是一个连接:
请注意,您可能想要使用
Single()
而不是First()
来明确表示您确实只期望一个单一结果。另一种选择是使用采用表达式的单个重载:
Well, it looks like that's probably a join:
Note that you might want to use
Single()
instead ofFirst()
to make it clear that you really do only expect a single result.Another option is to use the Single overload which takes an expression:
直接使用第二个表达式。这样,您就拥有了 Contact 对象,并且直接拥有了 contact 和 contactId
Use directly second expression. BY that, you have Contact object, And by that both contact and contactId directly
你可以这样做:
You could do:
当然可以,只是有没有用的问题。
Sure, you can, it's just a question of whether or not it would be useful to.