开发者

How to Query One to Many in Linq

开发者 https://www.devze.com 2023-03-10 04:48 出处:网络
--I have a Table named CLASS with the Following Records in it (PK) ClassID|Name ----------|---------- 1|CSE

--I have a Table named CLASS with the Following Records in it

     (PK)        
    ClassID   |   Name     
    ----------|----------
     1        |    CSE        
     2        |    ECE       

I have an another Table Named ALLOCATIONS which has the ForeighnKey Class_ID from 开发者_如何学GoCLASS table

   (PK)        (FK)
    ID   |   Class_ID   |   EffectiveFrom  |   Allocation
    -----|--------------|------------------|---------------
     1   |       1      |    10-May-2011   |      A
     2   |       1      |    10-May-2011   |      B
     3   |       1      |    14-June-2011  |      A
    ---------------------------------------|---------------
     4   |       2      |    14-June-2011  |      C   
     5   |       2      |    14-June-2011  |      D
     6   |       2      |    17-June-2011  |      C

I have the CSE & ECE Classes in an IQueryable[CLASS] variable, now i need the following Allocation Table Records based on the Highest EffectiveFrom Date like below:

   (PK)        (FK)
    ID   |   Class_ID   |   EffectiveFrom  |   Allocation
    -----|--------------|------------------|---------------
     2   |       1      |    10-May-2011   |      B
     3   |       1      |    14-June-2011  |      A
    ---------------------------------------|---------------
     5   |       2      |    14-June-2011  |      D
     6   |       2      |    17-June-2011  |      C

How to do it in LINQ (Preferable in LAMBDA Expression), i need the results in AllocationType not AnaymousType

Thank you!

Regards Pradeep


try:

from allocation in CurrentClasses.Allocations 
     group allocation by allocation.Class_ID
     into allocationGroups
     from allocationGroup in allocationGroups
     from allocationRow in allocationGroup
     where allocationRow.Date == allocationGroup.Max(x => x.Date)
     select allocationRow;

Hope that helps, sorry for the query syntax, but I haven't got much experience with joins in lambda.

0

精彩评论

暂无评论...
验证码 换一张
取 消