Skip to content

Instantly share code, notes, and snippets.

@SeppPenner
Last active March 27, 2019 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeppPenner/a082062d3ce2d5b8196bbf4618319044 to your computer and use it in GitHub Desktop.
Save SeppPenner/a082062d3ce2d5b8196bbf4618319044 to your computer and use it in GitHub Desktop.
IEnumerable gives error exception handeling can't read list
namespace ListExample
{
using System.Collections.Generic;
public class Program
{
private static readonly List<Animal> AnimalsToCheck = new List<Animal>
{
new Animal { Eater = Eater.Carnivore, Format = 1 },
new Animal { Eater = Eater.Herbivore, Format = 3 }
};
private static readonly List<Wagon> Wagons = new List<Wagon>
{
new Wagon(
1,
5,
1,
new List<Animal>
{
new Animal { Eater = Eater.Carnivore, Format = 5 },
new Animal { Eater = Eater.Herbivore, Format = 3 }
}),
new Wagon(
2,
9,
5,
new List<Animal>
{
new Animal { Eater = Eater.Carnivore, Format = 1 }
})
};
public static void Checker(List<Animal> listAnimals)
{
foreach (var animal in listAnimals)
{
// This is needed to not get an endless loop (Because the length of the list
// increases after each time the Add() method is called to Wagons).
var wagonCount = Wagons.Count;
for (var i = 0; i < wagonCount; i++)
{
var wagon = Wagons[i];
// This is needed to not get an endless loop (Because the length of the list
// increases after each time the Add() method is called to wagon.Animals).
var animalCount = wagon.Animals.Count;
for (var j = 0; j < animalCount; j++)
{
var wagonAnimal = wagon.Animals[j];
if (wagon.StartCapacity <= wagon.MaxCapacity
&& animal.Format + wagon.StartCapacity <= wagon.MaxCapacity
&& wagonAnimal.Eater == Eater.Carnivore && animal.Eater == Eater.Herbivore
&& animal.Format >= wagonAnimal.Format)
{
wagon.Animals.Add(animal);
Wagons.Add(wagon);
}
else
{
var newWagon = new Wagon();
newWagon.Animals.Add(animal);
Wagons.Add(newWagon);
}
}
}
var wag = new Wagon();
wag.Animals.Add(animal);
Wagons.Add(wag);
}
}
public static void Main()
{
Checker(AnimalsToCheck);
}
}
public class Animal
{
public Eater Eater { get; set; }
public int Format { get; set; }
}
public class Wagon
{
public List<Animal> Animals = new List<Animal>();
public Wagon()
{
}
public Wagon(int startCapacity, int maxCapacity, int format, List<Animal> animals)
{
this.StartCapacity = startCapacity;
this.MaxCapacity = maxCapacity;
this.Format = format;
this.Animals = animals;
}
public int Format { get; set; }
public int MaxCapacity { get; set; }
public int StartCapacity { get; set; }
}
public enum Eater
{
Carnivore,
Herbivore
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment