如果numberOfSchools等于0,如何设置年份?(C# LINQ)

0kjbasz6  于 2022-12-06  发布在  C#
关注(0)|答案(2)|浏览(146)

任务是从 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;
xa9qqrwz

xa9qqrwz1#

我将遍历year列表,然后基于匹配的year值创建新对象。

var result = yearList
        .Select(x => new
        {
            Year = x,
            NumberOfSchools = nameList
                .Where(y => y.Year == x)
                .DistinctBy(z => z.SchoolNumber)
                .Count()
        });
py49o6xq

py49o6xq2#

var grouped = nameList.GroupBy(e => e.Year);

return yearList
    .Select(year => new YearSchoolStat
    {
        Year = year,
        NumberOfSchools = grouped.FirstOrDefault(grouping => grouping.Key == year)?.Count() ?? 0
    })
    .OrderBy(x => x.NumberOfSchools);

相关问题