ex-oop-02-horse-race/HorseRace/HorseImporter.cs
2024-10-17 21:27:36 +02:00

78 lines
No EOL
1.8 KiB
C#

using System.Security.AccessControl;
namespace HorseRace;
public static class HorseImporter
{
public static bool TryReadHorses(string filePath, out Horse[]? horses)
{
horses = null;
if (!File.Exists(filePath))
{
return false;
}
string[] lines = File.ReadAllLines(filePath);
if (lines.Length <= 1)
{
return false;
}
return FormatLines(lines, out horses);
}
private static bool FormatLines(string[] lines, out Horse[]? horses)
{
lines = RemoveFirstLine(lines);
horses = new Horse[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
Horse.TryParse(lines[i], i + 1, out horses[i]!);
}
horses = TrimNullHorses(horses);
if (horses.Length == 0)
{
horses = Array.Empty<Horse>();
return false;
}
return true;
string[] RemoveFirstLine(string[] array)
{
string[] changedArray = new string[array.Length - 1];
for (int i = 0; i < changedArray.Length; i++)
{
changedArray[i] = array[i + 1];
}
return changedArray;
}
Horse[] TrimNullHorses(Horse?[] horses)
{
int count = 0;
foreach (var horse in horses)
{
if (horse != null)
{
count++;
}
}
Horse[] result = new Horse[count];
int index = 0;
for (var i = 0; i < horses.Length; i++)
{
var horse = horses[i];
if (horse != null)
{
result[index++] = horse;
}
}
return result;
}
}
}