Use PersonComparer's IComparer implementation to sort - CSharp Custom Type

CSharp examples for Custom Type:interface

Description

Use PersonComparer's IComparer implementation to sort

Demo Code

using static System.Console;
using System;//  w w  w  . j a v a2s .  c  om
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 PersonComparer's IComparer implementation to sort:");
      Array.Sort(people, new PersonComparer());
      foreach (var person in people)
      {
         WriteLine($"{person.Name}");
      }
   }
}
public class PersonComparer : IComparer<Person>
{
   public int Compare(Person x, Person y)
   {
      // Compare the Name lengths...
      int temp = x.Name.Length.CompareTo(y.Name.Length);
      /// ...if they are equal...
      if (temp == 0)
      {
         // ...then sort by the Names...
         return x.Name.CompareTo(y.Name);
      }
      else
      {
         // ...otherwise sort by the lengths.
         return temp;
      }
   }
}
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