开发者

How do I best combine these two LINQ expressions?

开发者 https://www.devze.com 2023-02-22 06:38 出处:网络
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

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.). Th开发者_StackOverflow中文版e 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();


Well, it looks like that's probably a join:

var contact = (from cm in DAL.dc.ContactMrns
               where cm.MRN == recipient.MRN
               join c in DAL.dc.Contacts on c.ContactID equals cm.ContactID
               select c).First();

Note that you might want to use Single() instead of First() 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:

var contact = DAL.dc.Contacts.Single
   (c => c.ContactID == DAL.dc.ContactMrns.Single
         (cm => cm.MRN == recipient.MRN).ContactID);


Use directly second expression. BY that, you have Contact object, And by that both contact and contactId directly


You could do:

var contact = DAL.dc.Contacts.First(
    c => c.ContactID == DAL.dc.ContactMrns.First(
        cm => cm.MRN == recipient.MRN));


Sure, you can, it's just a question of whether or not it would be useful to.

var contact = DAL.dc.Contacts.First(contact => 
       contact.ContactId == DAL.dc.ContactMrns.First(mrns =>
             mrns.MRN == recipient.MRN))
0

精彩评论

暂无评论...
验证码 换一张
取 消