using System; using System.Collections.Generic; using System.Linq; namespace doglist { public class DogClass { private static int iddog; public int Iddog { get; set; } public string Name { get; set; } public string Breed { get; set; } public bool IsBitch { get; set; } public int Age { get; set; } public DogClass() { Iddog = iddog++; } // static constructor to set isddog static DogClass() { iddog = 0; } public override string ToString() { return Name+'('+Iddog+") "+Breed + (IsBitch ?" B ":" D ") + "Age="+Age; } } public class DogList { private readonly List dogs; public List Dogs { get { return dogs; } } public int Count { get { return dogs.Count; } } public DogClass this[int i] { get { return dogs[i]; } } public void AddDog(DogClass dog) { dogs.Add(dog); } public void RemoveDog(DogClass dog) { dogs.Remove(dog); } public DogClass FindDog(int iddog) { return dogs.FirstOrDefault(Dog => Dog.Iddog == iddog); } public DogList() { dogs = new List {}; dogs.Capacity = 20; } public void ClearList() { dogs.Clear(); } // LINQ version of // foreach (var d in dogs) // yield return d; public IEnumerator GetEnumerator() { return ((IEnumerable) dogs).GetEnumerator(); } public int MySortFunction(DogClass dog1, DogClass dog2) { return dog1.Name.CompareTo(dog2.Name); } public void Sort() { dogs.Sort(MySortFunction); } } class Program { static void Main(string[] args) { var dogs = new DogList(); dogs.AddDog(new DogClass(){Name=@"Rufus",Breed="Minature Poodle",IsBitch = false,Age=4}); dogs.AddDog(new DogClass() {Name = @"Monty", Breed = "Minature Poodle", IsBitch = false,Age=5 }); dogs.AddDog(new DogClass() { Name = @"Sam", Breed = "Standard Poodle", IsBitch = false,Age=12 }); dogs.AddDog(new DogClass() { Name = @"Judy", Breed = "Afghanistan", IsBitch = true,Age=3 }); var dog = dogs.FindDog(2); Console.WriteLine("Dog 2 is {0}",dog); Console.WriteLine("There are {0} dogs",dogs.Count); Console.WriteLine("Dog[1] is {0}", dogs[1]); //dogs.Dogs.RemoveAll(adog => adog.IsBitch == false); var averagAge = 0; foreach (var adog in dogs) { averagAge += adog.Age; } Console.WriteLine("Average age is {0}", averagAge/dogs.Count); dogs.Sort(); Console.WriteLine("Male Dogs in alphaberic order by name"); foreach (var dog1 in dogs) { if (!dog1.IsBitch) { Console.WriteLine(dog1); } } Console.ReadKey(); } } }