0

我有一个 linq 查询,我需要进行分组以仅根据 testTypeId、testTakerId、subAreaId、subjectName、testDate.Value.Month、testDate.Value.Year 选择某个月份内的最高测试日期。

我遇到的问题是涉及嵌套列表的地方。有没有办法将数据展平以按 testTakerId、testTypeId、subAreaId、subjectName、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));
4

1 回答 1

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.

于 2013-07-19T15:48:02.217 回答