Skip to content

Commit

Permalink
📜Impleneted the method to convert the object Result to struct Planet
Browse files Browse the repository at this point in the history
📜Created class StringExtensions to implement method to convert string to int
  • Loading branch information
VictorDolzan committed Mar 23, 2024
1 parent 53f59e9 commit 86a1bd1
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ public async Task Run()
var root = JsonSerializer.Deserialize<Root>(json);

var planets = ToPlanets(root);

foreach (var planet in planets)
{
Console.WriteLine(planet);
}
}

private IEnumerable<Planet> ToPlanets(Root? root)
Expand All @@ -58,7 +63,15 @@ private IEnumerable<Planet> ToPlanets(Root? root)
throw new ArgumentNullException(nameof(root));
}

throw new NotImplementedException();
var planets = new List<Planet>();

foreach (var planetDto in root.results)
{
Planet planet = (Planet)planetDto;
planets.Add(planet);
}

return planets;
}

public readonly record struct Planet
Expand All @@ -79,5 +92,30 @@ public Planet(string name, int diameter, int? surfaceWater, int? population)
SurfaceWater = surfaceWater;
Population = population;
}

public static explicit operator Planet(Result planetDto)
{
var name = planetDto.name;
var diameter = int.Parse(planetDto.diameter);

int? population = planetDto.population.ToIntOrNull();
int? surfaceWater = planetDto.surface_water.ToIntOrNull();

return new Planet(name, diameter, surfaceWater, population);
}
}
}

public static class StringExtensions
{
public static int? ToIntOrNull(this string? input)
{
int? result = null;
if (int.TryParse(input, out int resultParsed))
{
result = resultParsed;
}

return result;
}
}

0 comments on commit 86a1bd1

Please sign in to comment.