The following example demonstrates how to provide a custom sort comparer that sorts addresses. The AddressComparer class (provided below) will first sort addresses which begin with numeric values by street name and then civic number. Address that do not have a civic number will be sorted alphabetically.
using System;
using System.Collections;
using System.Data;
namespace Xceed.Wpf.Documentation
{
publicclass AddressComparer: IComparer
{
public AddressComparer()
{
}
int IComparer.Compare( object x, object y )
{
string stringX = ( string )x;
string stringY = ( string )y;
conststring digits = "0123456789";
if( ( digits.IndexOf( stringX[ 0 ] ) >= 0 ) && ( digits.IndexOf( stringY[ 0 ] ) >= 0 ) )
{
int index = 0;
System.Text.StringBuilder xNumber = new System.Text.StringBuilder();
while( ( index < stringX.Length ) && ( digits.IndexOf( stringX[ index ] ) >= 0 ) )
{
xNumber.Append( stringX[ index ] );
index++;
}
index = 0;
System.Text.StringBuilder yNumber = new System.Text.StringBuilder();
while( ( index < stringY.Length ) && ( digits.IndexOf( stringY[ index ] ) >= 0 ) )
{
yNumber.Append( stringY[ index ] );
index++;
}
long xValue = long.Parse( xNumber.ToString() );
long yValue = long.Parse( yNumber.ToString() );
if( xValue > yValue )
return 1;
if( xValue < yValue )
return -1;
return stringX.CompareTo( stringY );
}
else
{
return stringX.CompareTo( stringY );
}
}
}
}
Requirements
Target Platforms: Windows 11, Windows 10, Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2