Returning a single property from a LINQ query resu

2020-02-25 07:38发布

问题:

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

回答1:

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;


回答2:

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


回答3:

var assocOrg = Contacts.
               Where(x => x.ContactTypeID == 2 && x.OrganizationName == "COMPANY XYZ").
               Select(x => x.contactId);


回答4:

var assocOrg = Contacts.Where(x => x.ContactTypeID == 2 && x.OrganizationName == "COMPANY XYZ").Select(x=> x.contactId).FirstOrDefault();

That would get you the first ContactId and the following would get you a list of ContactId's

var assocOrg = Contacts.Where(x => x.ContactTypeID == 2 && x.OrganizationName == "COMPANY XYZ").Select(x=> x.contactId);

In Sql style that would be

var assocOrg = from contact in Contacts
               where contact.ContactTypeId == 2 && contact.OrganizationName == "COMPANY XYZ"
               select contact.ContactId;


回答5:

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


标签: c# linq .net-4.0