以下を試してください。
私は次のエンティティを持っています。
//Person Entity
public class Person
{
public int PersonID { get; set; }
public string PersonName { get; set; }
}
//PersonAddress Entity
public class PersonAddress
{
public int PersonID { get; set; }
public int AddressID { get; set; }
public DateTime ValidFrom { get; set; }
}
次に、次のクエリを実行します。
//Get the latest ValidFrom for each person from PersonAddress.
var getLatestDateRecords =
from p in lstPersonAddress
group p by p.PersonID into g
select new
{
Infos =
(from PA in g
select new
{
PersonId = PA.PersonID
Date = g.Max(t=>t.ValidFrom)
}).Distinct()
};
//Segregate the ValidFroms and PersonId from the
//previous record set(getLatestDateRecords).
var segRecords =
from x in getLatestDateRecords
from y in x.Infos
select new { Date = y.Date, PersonId = y.PersonId };
//Obtain all the relevant information from the PersonAddress
// for the latest ValidFrom dates.
var allValidRecords =
from PA in lstPersonAddress
join x in segRecords
on PA.ValidFrom equals x.Date
where PA.PersonID == x.PersonId
select new {
PersonId = PA.PersonID
, AddressId = PA.AddressID
, Date = PA.ValidFrom
};
//Get the final result
var resultSet =
from p in lstPerson
join x in allValidRecords
on p.PersonID equals x.PersonId
select new
{
PersonId = p.PersonID
,PersonName = p.PersonName
,AddressId = x.AddressId,
Date = x.Date
};
いくつかのテストデータでうまく機能していることがわかりました。
ご不明な点がございましたら、お知らせください。