DenaliHardtail
DenaliHardtail

Reputation: 28296

How do I best combine these two LINQ expressions?

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();

Upvotes: 4

Views: 152

Answers (4)

Tejs
Tejs

Reputation: 41236

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))

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564363

You could do:

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

Upvotes: 0

archil
archil

Reputation: 39491

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499870

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);

Upvotes: 5

Related Questions