<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martijn's C# Programming Blog &#187; ICompare</title>
	<atom:link href="http://www.dijksterhuis.org/tag/icompare/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Sorting Generic Lists in C#</title>
		<link>http://www.dijksterhuis.org/sorting-generic-lists/</link>
		<comments>http://www.dijksterhuis.org/sorting-generic-lists/#comments</comments>
		<pubDate>Thu, 01 Jan 2009 05:07:32 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[generic]]></category>
		<category><![CDATA[ICompare]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[quicksort]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=427</guid>
		<description><![CDATA[Sorting a basic generic list in C# is trivial as long as you store basic elements such as strings or integers for which default comparison classes have been defined. In this post we will look into how we can reverse the string sort by implementing your own ICompare comparer, and how you can build your [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>Sorting a basic generic list in C# is trivial as long as you store basic elements such as strings or integers for which default comparison classes have been defined. In this post we will look into how we can reverse the string sort by implementing your own ICompare comparer, and how you can build your own comparison routines to compare other types. In the example we sort a list  (List<>) of people by both their name and their age.</em></p>
<p><span id="more-427"></span></p>
<p>The C# libraries already implement the Quicksort sorting algorithm. So for either a string or an int, sorting the list is as straightforward as calling &#8220;Sort&#8221;, as show in the below example. </p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;

namespace IComparer
{
    class MainClass
    {
        public static void Main(string[] args)
        {

            List&lt;string&gt; myList = new List&lt;string&gt;();

            myList.Add(&quot;z&quot;);
            myList.Add(&quot;c&quot;);
            myList.Add(&quot;a&quot;);
            myList.Add(&quot;d&quot;);
            myList.Add(&quot;b&quot;);

            myList.Sort();

            int cnt = 0;
            foreach(string letter in myList)
                Console.WriteLine(&quot;{0} = {1}&quot;,cnt++,letter);
        }
    }
}
</pre>
<p>This code will output:</p>
<pre class="brush: c#">
0 = a
1 = b
2 = c
3 = d
4 = z
</pre>
<p>But what to do if you would like to reverse the sorting order ? We will have to define our own reverse string comparison routine by sub-classing IComparer<string>. In the essential Compare function we simply call the standard String.Compare function with the parameters in reverse order:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;

namespace IComparer
{

    public class ReverseStringComparer : IComparer&lt;string&gt;
    {
        public int Compare(string x, string y)
        {
            // We reverse the result by flipping the input parameters
            return String.Compare(y,x);
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {

            List&lt;string&gt; myList = new List&lt;string&gt;();

            myList.Add(&quot;z&quot;);
            myList.Add(&quot;c&quot;);
            myList.Add(&quot;a&quot;);
            myList.Add(&quot;d&quot;);
            myList.Add(&quot;b&quot;);

            ReverseStringComparer myComparer = new ReverseStringComparer();        

            myList.Sort(myComparer);

            int cnt = 0;
            foreach(string letter in myList)
                Console.WriteLine(&quot;{0} = {1}&quot;,cnt++,letter);
        }
    }
}
</pre>
<p>This code will output:</p>
<pre class="brush: c#">
0 = z
1 = d
2 = c
3 = b
4 = a
</pre>
<p>Both strings and numbers are very basic types. If you want to sort a list build out of your own datatypes you will need to provide your own ICompare derived comparison class. In the following example we we create struct contained a basic personal record  with name, familyname and age. We provide two comparers, one that can sort the list by FamilyName and a second one that sorts the people in the list by their age.</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;

namespace IComparer
{

    struct Person
    {
        public string FamilyName;
        public string Name;
        public int    Age;
        public Person(string iFamilyName, string iName, int iAge)
        {
            FamilyName = iFamilyName; Name = iName; Age = iAge;
        }
    }

    class PersonComparerByName : IComparer&lt;Person&gt;
    {
        public int Compare(Person x, Person y)
        {
            return String.Compare(x.FamilyName,y.FamilyName);
        }
    }

    class PersonComparerByAge : IComparer&lt;Person&gt;
    {
        public int Compare(Person x, Person y)
        {
            return x.Age - y.Age;
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {

            List&lt;Person&gt; myList = new List&lt;Person&gt;();

            myList.Add( new Person(&quot;Mulder&quot;,&quot;Jan&quot;,22) );
            myList.Add( new Person(&quot;Dijkstra&quot;,&quot;Hans&quot;,45) );
            myList.Add( new Person(&quot;Zomer&quot;,&quot;Nara&quot;,25) );
            myList.Add( new Person(&quot;Italy&quot;,&quot;Jaro&quot;,38) );
            myList.Add( new Person(&quot;Robert&quot;,&quot;Nico&quot;,15) );

            // Sort the people in the list by their last name
            PersonComparerByName myComparerName = new PersonComparerByName();
            myList.Sort(myComparerName);

            int cnt1 = 0;
            foreach(Person aPerson in myList)
                Console.WriteLine(&quot;{0} = {1}&quot;,cnt1++,aPerson.FamilyName);

            // Sort the people in the list by their age
            PersonComparerByAge myComparerAge = new PersonComparerByAge();
            myList.Sort(myComparerAge);

            int cnt2 = 0;
            foreach(Person aPerson in myList)
                Console.WriteLine(&quot;{0} = {1} {2}&quot;,cnt2++,aPerson.FamilyName,aPerson.Age);

        }
    }
}
</pre>
<p>When run, the above code will output:</p>
<pre class="brush: c#">
0 = Dijkstra
1 = Italy
2 = Mulder
3 = Robert
4 = Zomer

0 = Robert 15
1 = Mulder 22
2 = Zomer 25
3 = Italy 38
4 = Dijkstra 45
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/sorting-generic-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
