我有一个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(),
};
答案 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
中只有一年的时间