Group By - 返回IEnumerable中唯一的唯一元素

时间:2012-07-06 19:45:49

标签: c# asp.net-mvc-3 linq entity-framework

我有一个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(),
           };

2 个答案:

答案 0 :(得分: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(),
    };

答案 1 :(得分:0)

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

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

如果我误解了这个问题,并且您希望ProgramYears属性中的每个每组,那么您可以在Select方法中进行以下更改:

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

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