2013-07-19 19 views
0

我有一個linq查詢,我需要根據testTypeId,testTakerId,subAreaId,subjectName,testDate.Value.Month,testDate.Value.Year進行分組,以便僅在某個月內選擇最高測試日期。在linq中展平數據

我遇到的問題是在嵌套列表關注。有沒有辦法通過testTakerId,testTypeId,subAreaId,主旨名稱,testDate.Value.Month,testDate.Value.Year扁平化的數據組。

非嵌套值(testTakerId,test.Value.Month等)做工精細,但與嵌套(subAreaId)值我有麻煩。

 var q1 = from entry in result 
       let testDate = entry.result.TestDate 
       where testDate != null 
       group entry by new { entry.testTakerId, entry.testInstance.Select(
       sr => sr.Subject.Select(c => c.subArea.Id)), entry.testInstance.Select(
       sr => sr.Subject.Select(c => c.subArea.Name)),entry.testInstance.Select(
       sr => sr.testInstance.Test.TestType.Id), testDate.Value.Month, 
        testDate.Value.Year } into g 
       select g.Where(entry => entry.result.TestDate == g.Max(e => e.result.TestDate)); 
+1

好像你正在尋找['SelectMany'(http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx),從快速脫脂。 –

+0

我需要一個簡單的屬性,而不是與嵌套屬性條目列表。 – Rayshawn

回答

1

必須扁平化的結果通過與包含的集合(testInstanceSubject)的連結第一組,然後做分組:

var q1 = from entry in result 
     from ti in entry.testInstance // translates to a SQL join 
     from su in ti.Subject   // translates to a SQL join 
     let testDate = entry.result.TestDate 
     where testDate != null 
     group entry by new 
     { 
      entry.testTakerId, 
      su.subArea.Id, 
      su.subArea.Name, 
      ti.Test.TestType.Id, 
      testDate.Value.Month, 
      testDate.Value.Year 
     } 
     into g 
     select g.Where(entry => entry.result.TestDate == 
            g.Max(e => e.result.TestDate)); 

在流利(或方法)語法像from ti in entry.testInstance一個說法相當於SelectMany

+0

太棒了,效果很好,非常感謝。好的解釋「sql join」的翻譯。 – Rayshawn