public async Task <IActionResult> GetSelectionsForSpecificationsSelectedForFunding() { ApiResponse <IEnumerable <SpecificationSummary> > apiResponse = await _specificationsApiClient.GetSpecificationsSelectedForFunding(); if (apiResponse.StatusCode == HttpStatusCode.OK) { List <SpecificationSummary> specifications = apiResponse.Content.ToList(); List <FundingStreamWithSpecificationSelectedForFundingModel> fundingStreams = specifications .SelectMany(x => x.FundingStreams.Select(fs => new FundingStreamWithSpecificationSelectedForFundingModel { Id = fs.Id, Name = fs.Name })) .DistinctBy(x => x.Id) .ToList(); foreach (FundingStreamWithSpecificationSelectedForFundingModel fundingStream in fundingStreams) { List <SpecificationSummary> streamSpecs = specifications .Where(x => x.FundingStreams.Any(s => s.Id == fundingStream.Id)).ToList(); IEnumerable <Reference> fundingPeriods = streamSpecs .Select(y => y.FundingPeriod) .DistinctBy(x => x.Id); foreach (Reference fundingPeriod in fundingPeriods) { IEnumerable <SpecificationSummary> periodSpecs = streamSpecs .Where(x => x.FundingPeriod.Id == fundingPeriod.Id); fundingStream.Periods.Add(new FundingPeriodWithSpecificationSelectedForFundingModel { Id = fundingPeriod.Id, Name = fundingPeriod.Name, Specifications = periodSpecs .Select(s => new SpecificationSelectedForFundingModel { Id = s.Id, Name = s.Name }) .DistinctBy(x => x.Id) }); } } return(Ok(fundingStreams)); } if (apiResponse.StatusCode == HttpStatusCode.BadRequest) { return(new BadRequestResult()); } return(new StatusCodeResult(500)); }