apieceoffruit

Animals

Jun 25th, 2021 (edited)
930
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.88 KB | None | 0 0
  1. public class Animals : IEnumerable<Animal>
  2. {
  3.     public void Add<T>(T animal) where T : Animal
  4.     {
  5.         var type = typeof(T);
  6.         if (!_animals.ContainsKey(type)) _animals[type] = new List<Animal>();
  7.         _animals[type].Add(animal);
  8.     }
  9.  
  10.     public IEnumerable<T> GetAll<T>() where T : Animal
  11.     {
  12.         var type = typeof(T);
  13.         return _animals.ContainsKey(type) ? (IEnumerable<T>) _animals[type] : Enumerable.Empty<T>();
  14.     }
  15.  
  16.     public IEnumerable<Animal> GetAll()
  17.     {
  18.         var animals = new List<Animal>();
  19.         foreach (var kvp in _animals)
  20.             animals.AddRange(kvp.Value);
  21.         return animals;
  22.     }
  23.  
  24.     Dictionary<Type, List<Animal>> _animals = new Dictionary<Type,  List<Animal>>();
  25.  
  26.     public IEnumerator<Animal> GetEnumerator() => GetAll().GetEnumerator();
  27.     IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  28. }
Add Comment
Please, Sign In to add comment