1

我有一个 LINQ to Entities 查询,我只需要返回“ProgramYears”的唯一实例,这样我就可以在我的视图中遍历它们。我不知道如何改变它,这样我就不会得到重复。

var data = from SurveyProgramModel in surveyProgramRepository.Get()
                       where SurveyProgramModel.ProgramYear == ProgramYear
                       group SurveyProgramModel by SurveyProgramModel.ProgramTypeId into programTypeGroup
           select new ProgramTypeViewModel()
           {

               ProgramTypeIds = programTypeGroup.Key,
               ProgramIds = programTypeGroup.Select(r => r.ProgramId),
               ProgramYears = programTypeGroup.Select(r => r.ProgramYear),
               ProgramTitles = programTypeGroup.Select(r => r.ProgramTitle),
               ProgramTypes = programTypeGroup.Select(r => r.ProgramType.ProgramType).Distinct(),
           };
4

2 回答 2

2

可以使用Distinct运营商吗?

(from SurveyProgramModel in surveyProgramRepository.Get()
 where SurveyProgramModel.ProgramYear == ProgramYear
 group SurveyProgramModel by SurveyProgramModel.ProgramTypeId)
.Distinct()
.Select(programTypeGroup => new ProgramTypeViewModel()
    {
        ProgramTypeIds = programTypeGroup.Key,
        ProgramIds = programTypeGroup.Select(r => r.ProgramId),
        ProgramYears = programTypeGroup.Select(r => r.ProgramYear),
        ProgramTitles = programTypeGroup.Select(r => r.ProgramTitle),
        ProgramTypes = programTypeGroup.Select(r => r.ProgramType.ProgramType).Distinct(),
    };
于 2012-07-06T19:50:16.713 回答
0

这将为您提供您想要的不同年份:

var years = surveyProgramRepository.Get()
           .Select(x => x.ProgramYear).Distinct();

或者,如果我误解了这个问题,并且您想要每组财产的不同年份ProgramYears,您可以在您的方法中进行以下更改Select

...
ProgramYears = programTypeGroup.Select(r => r.ProgramYear).Distinct(),
...

(但正如评论中所述,这没有意义,因为您已经使用 过滤了一年where,因此每个组在 中只有一年ProgramYears

于 2012-07-06T20:53:15.580 回答