What is the best way to combine these two LINQ expressions?

The first expression obtains the contact identifier using a different identifying value. The second expression gets the entire contact using the contact identifier. It seems to me that I can combine these two statements into one, but I struggle too much (tired, embarrassed, made stupid mistakes, etc.). These two statements work, and I get the result that I need, but I feel that it can be cleaner and, possibly, with one expression.

Thanks for the 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(); 
+4
source share
4 answers

Well, it seems like a connection is possible:

 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 can use Single() instead of First() so that it is clear that you really expect only one result.

Another option is to use a single overload that takes an expression :

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

You can do:

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

Use the direct second expression. In addition, you have a contact object, and this both directly and contactId

0
source

Of course you can, it's just a question of whether it will be useful.

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

Source: https://habr.com/ru/post/1346944/


All Articles