Use Person's IComparable implementation to sort - CSharp Custom Type

CSharp examples for Custom Type:interface

Description

Use Person's IComparable implementation to sort

Demo Code

using static System.Console;
using System;//from  www  .jav  a 2  s . c  o  m
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
   static void Main(string[] args)
   {
      Person[] people =
      {
         new Person { Name = "A" },
         new Person { Name = "B" },
         new Person { Name = "C" },
         new Person { Name = "D" }
      };
      WriteLine("Initial list of people:");
      foreach (var person in people)
      {
         WriteLine($"{person.Name}");
      }
      WriteLine("Use Person's IComparable implementation to sort:");
      Array.Sort(people);
      foreach (var person in people)
      {
         WriteLine($"{person.Name}");
      }
   }
}
public class Person : IComparable<Person>
{
   public string Name;
   public DateTime DateOfBirth;
   public List<Person> Children = new List<Person>();
   public int CompareTo(Person other)
   {
      return Name.CompareTo(other.Name);
   }
}

Result


Related Tutorials