<?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>On technology and development &#187; reflection</title>
	<atom:link href="http://blog.codewrench.net/tag/reflection/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.codewrench.net</link>
	<description>My thoughs on stuff</description>
	<lastBuildDate>Wed, 18 Jan 2012 07:49:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Sorting a generic list on arbitrary property (C#)</title>
		<link>http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/</link>
		<comments>http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 16:20:58 +0000</pubDate>
		<dc:creator>Pål</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[Source]]></category>

		<guid isPermaLink="false">http://blog.paks.no/?p=259</guid>
		<description><![CDATA[I often need to sort a generic list on some arbitrary property. After writing the code a couple of times I decided to make it more generic using generics and some reflection. Oh, I know that reflection if costly and &#8230; <a href="http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I often need to sort a generic list on some arbitrary property. After writing the code a couple of times I decided to make it more generic using generics and some reflection. Oh, I know that reflection if costly and this is not a good way to sort large lists, but I typically work with small lists.<br />
<span id="more-259"></span></p>
<pre lang="csharp">
public enum SortDirection
{
   Ascending, Descending
}

public class ListSorter where T : class
{
  public static List Sort
(
              List<T> listToSort,
              string propertyName,
              SortDirection direction) where P : IComparable
  {
    Type propertyType = typeof (P);
    Type comparableInterface = propertyType.GetInterface("IComparable");

    if (comparableInterface == null)
        throw new Exception("Properties to sort by must be IComparable");

    listToSort.Sort(
        delegate(T x, T y)
            {
              PropertyInfo p1 = x.GetType().GetProperty(propertyName, propertyType);
              PropertyInfo p2 = y.GetType().GetProperty(propertyName, propertyType);

              object p1objvalue = p1.GetValue(x, null);
              object p2objvalue = p2.GetValue(y, null);

              P p1value = (P)p1objvalue;
              P p2value = (P)p2objvalue;

              if (direction == SortDirection.Ascending)
                  return p1value.CompareTo(p2value);
              else
                  return p2value.CompareTo(p1value);
          });

    return listToSort;
  }
}
</pre>
<p>To sort a list of Person objects by the string property FirstName do the following:</p>
<pre lang="csharp">
List<Person> myUnsortedList = GetPersonsInRandomOrder();
List<Person> sortedList =  ListSorter
                                     .Sort(
                                     myUnsortedList,
                                     "FirstName",
                                     SortDirection.Ascending);
</pre>
<p>To sort a list of Person objects by the int property Age do the following:</p>
<pre lang="csharp">
List<Person> myUnsortedList = GetPersonsInRandomOrder();
List<Person> sortedList =  ListSorter
                                     .Sort(
                                     myUnsortedList,
                                     "Age",
                                     SortDirection.Ascending);
</pre>
<p>If you have the luxury of using .NET Framework 3.0 or 3.5 you can use Linq to solve the problem really quick:</p>
<pre lang="csharp">

var sortedPersonList = from p in unsortedPersonList
                               orderby p.FirstName
                               select p;

foreach (var person in sortedPersonList)
{
    Console.WriteLine(person.FirstName + " " + person.LastName);
}
</pre>
<p>Leave a comment to this post if you have any thoughts.</p>
<style>
 #sidebars {    visibility: hidden;    display: none; }
 #content { width: 860px; }
</style>
]]></content:encoded>
			<wfw:commentRss>http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

