Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created October 25, 2017 20:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jianminchen/d5a52ec62e909567e0ae33e463320ef9 to your computer and use it in GitHub Desktop.
C sharp 2000 things - Item 137 - – Sorting an Array Using an Independent Comparer Method
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Item137_Sort
{
/// <summary>
/// C# 2000 things
/// https://csharp.2000things.com/2010/11/01/137-sorting-an-array-using-an-independent-comparer-method/
/// #137 – Sorting an Array Using an Independent Comparer Method
/// Instead of extending a type to implement IComparable to allow sorting, you can create a separate class
/// that knows how to compare objects of that type and use the new class to do the sorting.
///
/// Here’s an example of sorting objects of type Person using a custom Compare method. To start with,
/// we define a new class that implements IComparer.
/// </summary>
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
/// <summary>
///
/// </summary>
public class PersonSorter : IComparer
{
public int Compare(object o1, object o2)
{
Person p1 = o1 as Person;
Person p2 = o2 as Person;
// Sort by LastName, then by FirstName (ignore case)
int compare = p1.LastName.ToLower().CompareTo(p2.LastName.ToLower());
if (compare == 0)
{
compare = p1.FirstName.ToLower().CompareTo(p2.FirstName.ToLower());
}
return compare;
}
}
class Program
{
/// <summary>
/// Now we can sort using this compare function by passing an instance of the IComparer
/// class into the Sort method.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Person[] folks = new Person[4];
folks[0] = new Person("Bronte", "Emily");
folks[1] = new Person("Bronte", "Charlotte");
folks[2] = new Person("Tennyson", "Alfred");
folks[3] = new Person("Mailer", "Norman");
Array.Sort(folks, new PersonSorter());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment