Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a single property from a LINQ query result

Tags:

c#

linq

.net-4.0

The following expression returns a contact - the whole contact with dozens of properties. This is fine but, ideally, I'd like the return to be the contact's id (contact.contactId) property only. How do I do this?

var assocOrg = Contacts.Where(x => x.ContactTypeID == 2 && x.OrganizationName == "COMPANY XYZ");
like image 522
DenaliHardtail Avatar asked Nov 26 '10 18:11

DenaliHardtail


2 Answers

var result = Contacts.Where(x => ...)
                     .Select(x => x.ContactID);

or

var result = from x in Contacts
             where x.ContactTypeID == 2 && x.OrganizationName == "COMPANY XYZ"
             select x.ContactID;
like image 88
dtb Avatar answered Oct 03 '22 13:10

dtb


If you want to get a single or first object matching your conditions , use this :

  var result = Contacts.Where(x => ...)
   .Select(x => x.ContactID).FirstOrDefault();
like image 23
Baqer Naqvi Avatar answered Oct 03 '22 12:10

Baqer Naqvi