问题
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();
来源:https://stackoverflow.com/questions/4287789/returning-a-single-property-from-a-linq-query-result