Home > Back-end >  How to set year if numberOfSchools equal to 0? (C# LINQ)
How to set year if numberOfSchools equal to 0? (C# LINQ)

Time:08-25

The task is to get data about the number of different schools that students graduated from, for each year from yearList

Example:

                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}
                });

I got the right result, but if the NumberOfSchools equal to 0, the Year is also equal to 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;

CodePudding user response:

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);

CodePudding user response:

I would iterate through year list, then create new objects based on matching year values.

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