Guest User

Untitled

a guest
Dec 16th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.90 KB | None | 0 0
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             Console.WriteLine("Hello World!");
  6.             var cats = new List<Cat>
  7.             {
  8.                 new Cat{Name = "Mr Muffins", Weight=10, Age = 4},
  9.                 new Cat { Name = "Mr Bigglesworth", Weight = 15, Age = 6 }
  10.             };
  11.             //Sort by name
  12.             cats.Sort(new CatNameComparer());
  13.             //Sort by age
  14.             cats.Sort(new CatAgeComparer());
  15.        
  16.         }
  17.     }
  18.  
  19.     class Cat
  20.     {
  21.         public string Name{ get; set; }
  22.         public double Weight { get; set; }
  23.         public int Age { get; set; }
  24.     }
  25.  
  26.     class CatNameComparer : IComparer<Cat>
  27.     {
  28.         public int Compare([AllowNull] Cat x, [AllowNull] Cat y)
  29.         {
  30.             return new CaseInsensitiveComparer().Compare(x.Name, y.Name);
  31.         }
  32.     }
  33.  
  34.     class CatAgeComparer : IComparer<Cat>
  35.     {
  36.         public int Compare([AllowNull] Cat x, [AllowNull] Cat y)
  37.         {
  38.             if (x.Age > y.Age)
  39.                 return 1;
  40.  
  41.             if (x.Age < y.Age)
  42.                 return -1;
  43.  
  44.             else
  45.                 return 0;
  46.         }
  47.     }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment