任务是从 yearList 中获取每年学生毕业的不同学校数量的数据
示例:
nameList: new[]
{
new Entrant {LastName = "Name", SchoolNumber = 12, Year = 2019},
new Entrant {LastName = "Name", SchoolNumber = 13, Year = 2019},
new Entrant {LastName = "Name", SchoolNumber = 12, Year = 2019},
new Entrant {LastName = "Name", SchoolNumber = 14, Year = 2016},
new Entrant {LastName = "Name", SchoolNumber = 15, Year = 2016},
new Entrant {LastName = "Name", SchoolNumber = 12, Year = 2018},
new Entrant {LastName = "Name", SchoolNumber = 12, Year = 2018},
new Entrant {LastName = "Name", SchoolNumber = 13, Year = 2018},
new Entrant {LastName = "Name", SchoolNumber = 12, Year = 2017},
new Entrant {LastName = "Name", SchoolNumber = 12, Year = 2017}
},
yearList: new[] { 2020, 2017, 2018 },
expected: new[]
{
new YearSchoolStat {NumberOfSchools = 0, Year = 2020},
new YearSchoolStat {NumberOfSchools = 1, Year = 2017},
new YearSchoolStat {NumberOfSchools = 2, Year = 2018}
});
我得到了正确的结果,但如果 NumberOfSchools 等于0,则 Year 也等于0
var groupedYear = yearList.GroupBy(x => x);
var groupedSchoolNumber = groupedYear.Select(y => nameList.Where(x => x.Year == y.Key)).Select(group => group.GroupBy(item => item.SchoolNumber));
var result = groupedSchoolNumber.Select(s => new YearSchoolStat { NumberOfSchools = s.Count(), Year = s.Select(y => y.Select(x => x.Year).FirstOrDefault()).FirstOrDefault() }).OrderBy(x => x.NumberOfSchools);
return result;
2条答案
按热度按时间xa9qqrwz1#
我将遍历year列表,然后基于匹配的year值创建新对象。
py49o6xq2#