2017-03-20 1 views
0

에 의해 엔티티이고 테이블 구조 -가입 및 그룹 여기에 LINQ에서

나는 (사람에서으로 PersonName 및 보고서 테이블에서 신분증의 마지막 레코드) 다음과 같이 데이터를 선택합니다
class Person { int PersonId, string PersonName} 
class Report { int ReportId, datetime ReportTime, int PersonId } 

Table: Persons 
---------------------------- 
| PersonId | PersonName | 
---------------------------- 
| 1  | Abc  | 
---------------------------- 
| 2  | Xyz  | 
---------------------------- 

Table: Reports 
---------------------------------------------- 
| ReportId | ReportTime  | PersonId | 
---------------------------------------------- 
| 10  | 2017-02-27 11:12 | 1  | 
---------------------------- ----------------- 
| 14  | 2017-02-27 15:23 | 1  | 
---------------------------- ----------------- 

-

------------------------------------- 
| PersonName |  ReportTime  | 
------------------------------------- 
| Abc  | 2017-02-27 15:23 | 
------------------------------------- 

람다 또는 LINQ에서 어떻게 할 수 있습니까?

+0

지금 어떤 오류를 지정하십시오. 코드가 없으면 명확하지 않습니다. –

+0

코드 복사 - 복사에 도움이 필요합니까? –

답변

0

이 시도 :

 List<Person> people = new List<Person> 
     { 
      new Person {PersonId = 1, PersonName = "AB" }, 
      new Person {PersonId = 2, PersonName = "CD" }, 
      new Person {PersonId = 3, PersonName = "EF" }, 
     }; 

     List<Report> reports = new List<Report>() 
     { 
      new Report {ReportId = 1, ReportTime = DateTime.Now, PersonId = 1 }, 
      new Report {ReportId = 2, ReportTime = DateTime.Now.AddHours(-1), PersonId = 1 }, 
      new Report {ReportId = 3, ReportTime = DateTime.Now.AddHours(-2), PersonId = 1 }, 
      new Report {ReportId = 4, ReportTime = DateTime.Now.AddMinutes(-3), PersonId = 2 }, 
      new Report {ReportId = 5, ReportTime = DateTime.Now, PersonId = 2 } 
     }; 


     var res = (from rep in reports 
        group rep by rep.PersonId into repGrp 
        join ppl in people on repGrp.FirstOrDefault().PersonId equals ppl.PersonId 
        select new 
        { 
         PersonName = ppl.PersonName, 
         ReportDate = repGrp.Max(r => r.ReportTime), 
        }).ToList(); 
    } 
2

사용 Queryable.GroupJoin을 :

from p in db.Persons 
join r in db.Reports on p.PersonId equals r.PersonId into g 
where g.Any() // if some persons do not have reports 
select new { 
    p.PersonName, 
    ReportTime = g.Max(r => r.ReportTime) 
} 

람다

db.Persons.GroupJoin(
    db.Reports, 
    p => p.PersonId, 
    r => r.PersonId, 
    (p,g) => new { p.PersonName, ReportTime = g.Max(r => (DateTime?)r.ReportTime) }) 
(는보고를하지 않는 사람을위한 null로 null 허용 ReportTime를 반환 않습니다)