使用连接在linq中的一列上区分开来

时间:2013-11-14 07:04:51

标签: linq

我知道我们可以使用以下查询在一列上区分: 我知道我们可以使用以下查询在一列上区分:

SELECT  *
FROM    (SELECT A, B, C,
                ROW_NUMBER() OVER (PARTITION BY B ORDER BY A) AS RowNumber
         FROM   MyTable
         WHERE  B LIKE 'FOO%') AS a
WHERE   a.RowNumber = 1

我在我的情况下使用了类似的SQL查询,我加入了多个表,但我的项目是在mvc4中,我需要linq到相同的实体。这是我的代码:

select * from
(
select fp.URN_No, 
ROW_NUMBER() OVER 
   (PARTITION BY pdh.ChangedOn ORDER BY fp.CreatedOn)
   as num,

fp.CreatedOn, pdh.FarmersName, pdh.ChangedOn, cdh.Address1,  cdh.State, ich.TypeOfCertificate, ich.IdentityNumber, bdh.bankType, bdh.bankName,
pidh.DistrictId,  pidh.PacsRegistrationNumber,  idh.IncomeLevel, idh.GrossAnnualIncome

from MST_FarmerProfile as fp inner join PersonalDetailsHistories as pdh on fp.personDetails_Id = pdh.PersonalDetails_Id
inner join ContactDetailsHistories as cdh on fp.contactDetails_Id = cdh.ContactDetails_Id
inner join IdentityCertificateHistories as ich on fp.IdentityCertificate_Id = ich.IdentityCertificate_Id
inner join BankDetailsHistories as bdh on fp.BankDetails_Id = bdh.BankDetails_Id
left join PacInsuranceDataHistories as pidh on fp.PacsInsuranceData_Id = pidh.PacsInsuranceData_Id
left join IncomeDetailsHistories as idh on fp.IncomeDetails_Id = idh.IncomeDetails_Id

where URN_No in(
select distinct MST_FarmerProfile_URN_No from PersonalDetailsHistories where MST_FarmerProfile_URN_No in(
select URN_No from MST_FarmerProfile where (CreatedOn>=@fromDate and CreatedOn<= @toDate and Status='Active')))
)a where a.num=1

1 个答案:

答案 0 :(得分:2)

从sql获取结果后使用此linq查询。 p.ID是你想要的不同列名

List<Person> distinctRecords = YourResultList
            .GroupBy(p => new { p.ID})
            .Select(g => g.First())
            .ToList();