从LINQ查询结果返回单个属性

时间:2010-11-26 18:40:08

标签: c# linq .net-4.0

以下表达式返回一个联系人 - 与几十个属性的整个联系人。这很好,但理想情况下,我希望返回只是联系人的id(contact.contactId)属性。我该怎么做?

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

5 个答案:

答案 0 :(得分:33)

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

var result = from x in Contacts
             where x.ContactTypeID == 2 && x.OrganizationName == "COMPANY XYZ"
             select x.ContactID;

答案 1 :(得分:3)

如果您想获得符合条件的单个或第一个对象,请使用:

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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

这样可以获得第一个ContactId,以下内容可以为您提供ContactId的列表

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

在Sql样式中

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

答案 4 :(得分:1)

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