Skip to content

Instantly share code, notes, and snippets.

@Lanse505
Created November 10, 2021 01:45
Show Gist options
  • Save Lanse505/067f0e22f4ef74d62961961fb8cf029a to your computer and use it in GitHub Desktop.
Save Lanse505/067f0e22f4ef74d62961961fb8cf029a to your computer and use it in GitHub Desktop.
Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
at System.Collections.Generic.List`1.get_Item(Int32 index)
at FirstAssignment.Writer.TableWriter.<>c__DisplayClass11_0.<ToString>b__0(Int32 size) in F:\RiderProjects\FirstAssignment\FirstAssignment\Writer\TableWriter.cs:line 64
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.Aggregate[TSource](IEnumerable`1 source, Func`3 func)
at FirstAssignment.Writer.TableWriter.ToString() in F:\RiderProjects\FirstAssignment\FirstAssignment\Writer\TableWriter.cs:line 62
at FirstAssignment.Writer.TableWriter.Print() in F:\RiderProjects\FirstAssignment\FirstAssignment\Writer\TableWriter.cs:line 94
at FirstAssignment.Program.Main(String[] args) in F:\RiderProjects\FirstAssignment\FirstAssignment\Program.cs:line 97
Process finished with exit code -532,462,766.
using System;
using System.Collections.Generic;
using System.Threading;
using FirstAssignment.Writer;
namespace FirstAssignment{
internal class Program{
private readonly struct Person{
public Person(int index, string name, int age, int ageInYears){
Index = index;
Name = name;
Age = age;
Ageinyears = ageInYears;
}
public int Index{ get; }
public string Name{ get; }
public int Age{ get; }
public int Ageinyears{ get; }
}
public static void Main(string[] args){
var familyWriter = new TableWriter("id", "namn", "ålder");
var expandedWriter = new TableWriter("id", "namn", "ålder", "ålder i dagar", "äldst", "yngst");
var expandedContent = new List<Person>();
Console.WriteLine("Välkommen till Familje-Kalkylatorn!");
DramaticPause();
Console.WriteLine("Låt oss starta!");
LongSleep();
Console.WriteLine("Vill du köra i 'Extended Information' läge?");
Console.WriteLine("Y = Yes, N = No");
var extendedInformation = Console.ReadLine();
if (extendedInformation == null || extendedInformation.ToUpper() != "Y" && extendedInformation.ToUpper() != "N"){
throw new ArgumentException("'Extended Information Mode' didn't receive a corrent input, should either be Y or N");
}
for (var i = 0; i < 4; i++){
var printable = $"Namnge familjemedlem {i + 1}";
Console.WriteLine(printable);
var name = Console.ReadLine();
ShortSleep();
Console.WriteLine("Vad är åldern på denna familjemedlem?");
var age = Console.ReadLine();
ShortSleep();
Console.WriteLine();
Console.WriteLine("Fantastiskt, Registrerar din familje medlem nu!");
LongSleep();
switch (extendedInformation.ToUpper()){
case "N":
familyWriter.AddRow(i, name, age);
break;
case "Y":{
var ageInt = ValidateAndFormatAge(age);
var person = new Person(i, name, ageInt, ageInt * 365);
expandedContent.Add(person);
break;
}
}
}
if (extendedInformation.ToUpper() != "Y") return;
{
var oldestById = new KeyValuePair<int, int>();
var youngestById = new KeyValuePair<int, int>();
foreach (var person in expandedContent){
if (person.Age > oldestById.Value){
oldestById = new KeyValuePair<int, int>(person.Index, person.Age);
}
if (person.Age < youngestById.Value){
youngestById = new KeyValuePair<int, int>(person.Index, person.Age);
}
}
foreach (var person in expandedContent){
var isOldest = person.Index == oldestById.Key;
var isYoungest = person.Index == youngestById.Key;
expandedWriter.AddRow(person.Index, person.Name, person.Age, person.Ageinyears, isOldest, isYoungest);
}
}
WriteEmptyLines(3);
Console.WriteLine("Tabulerar!");
DramaticPause();
Console.WriteLine();
if (extendedInformation.ToUpper() != "Y"){
familyWriter.Print();
}
else{
expandedWriter.Print();
}
}
private static int ValidateAndFormatAge(string age){
int ageInt;
try{
ageInt = int.Parse(age);
}
catch (Exception e){
Console.WriteLine(e);
throw;
}
return ageInt;
}
private static void ShortSleep(){
Thread.Sleep(500);
}
private static void LongSleep(){
Thread.Sleep(1500);
}
private static void DramaticPause(){
for (int j = 0; j < 3; j++){
Thread.Sleep(1000);
Console.Write(".");
}
Console.WriteLine();
}
private static void WriteEmptyLines(int amount){
for (int i = 0; i < amount; i++){
Console.WriteLine();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstAssignment.Writer{
public class TableWriter{
private List<object> Columns{ get; set; }
private List<object[]> Rows{ get; set; }
public TableWriter(params string[] columns){
if (columns == null || columns.Length == 0){
throw new ArgumentException("Input Arguments are either null or none provided!");
}
Columns = new List<object>(columns);
Rows = new List<object[]>();
}
// Adds the content rows to the table
public void AddRow(params object[] values){
// Input validation, throws if: The values param is null, The values param is empty, The values param doesn't match up with the columns size.
if (values == null || values.Length == 0 || values.Length != Columns.Count){
throw new ArgumentException("Input arguments are either: Null, Input values were 0, or the number of Input values didn't match the number of columns");
}
Rows.Add(values);
}
// Gets a list of the greatest found sizes of entries in each column.
// Aka if row 4 has the longest string, it will get added to this list as the fourth entry.
private List<int> GetMaxStringLength(){
List<int> colSize = new List<int>();
// Cycles over each row and column and finds the longest possible entry for each column to determine the content width needed for the table.
for (int i = 0; i < colSize.Count; i++){
List<object> colRow = new List<object>();
int greatestLength = 0;
colRow.Add(Columns[i]);
colRow.AddRange(Rows.Select(t => t[i]));
for (int k = 0; k < colRow.Count; k++){
int length = colRow[k].ToString().Length;
if (length > greatestLength){
greatestLength = length;
}
}
colSize.Add(greatestLength);
}
return colSize;
}
public override string ToString(){
StringBuilder tableString = new StringBuilder();
List<int> colSize = GetMaxStringLength();
// This handles and deals with formatting out rows and columns into something we can work with.
string rowFormat = Enumerable // Creates an Enumerable (Countable)
.Range(0, Columns.Count) // With a Range of 0-(Size of _columns)
.Select(size => " | {" + size + ",-" + colSize[size] + "}") // Loops through the range with the columns maximum length
.Aggregate((sum, nextValue) => sum + nextValue) + " |"; // Sums it all together
string columnHeaders = string.Format(rowFormat, Columns.ToArray()); // Creates the formatted Header string
List<string> values = Rows.Select(row => string.Format(rowFormat, row)).ToList(); // formats out rows and outputs them as a joint list of strings.
// Grabs the longest row length.
int maxRowSize = Math.Max(0, Rows.Any() ? Rows.Max(row => string.Format(rowFormat, row).Length) : 0);
// Finalizes the final table divider line size.
int maxColSize = Math.Max(maxRowSize, columnHeaders.Length);
string divLine = string.Join("", Enumerable.Repeat("-", Math.Min(maxColSize - 1, 0)));
string divider = $" {divLine} ";
// Time to build this Lego Table!
tableString.AppendLine(divider); // Adds the top divider line
tableString.AppendLine(columnHeaders); // adds the column header line
// Loops through all of our finalized row strings
foreach (var row in values){
tableString.AppendLine(divider); // Adds a divider line
tableString.AppendLine(row); // Adds the content row string
}
tableString.AppendLine(divider); // adds an ending divider line
return tableString.ToString();
}
// Prints the finalized table!
public void Print(){
Console.WriteLine(ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment