Returning a single property from a LINQ query result

北城余情 提交于 2020-01-20 21:06:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!