<p>So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.</p>

<p>Turns out the IList interface doesn't have a sort method built in. </p>

<p>I ended up using the <code>ArrayList.Adapter(list).Sort(new MyComparer())</code> method to solve the problem but it just seemed a bit "ghetto" to me.</p>

<p>I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.</p>

<p>So my question is, does anyone have an elegant solution to sorting an IList</p>

[{'answer_id': 15491, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 3, 'selected': False, 'text': "<p>You're going to have to do something like that i think (convert it into a more concrete type).</p>\n\n<p>Maybe take it into a List of T rather than ArrayList, so that you get type safety and more options for how you implement the comparer.</p>\n"}, {'answer_id': 15492, 'author': 'lubos hasko', 'author_id': 275, 'author_profile': 'https://Stackoverflow.com/users/275', 'pm_score': -1, 'selected': False, 'text': '<p>Convert your <code>IList</code> into <code>List&lt;T&gt;</code> or some other generic collection and then you can easily query/sort it using <code>System.Linq</code> namespace (it will supply bunch of extension methods)</p>\n'}, {'answer_id': 15494, 'author': 'Brad Leach', 'author_id': 708, 'author_profile': 'https://Stackoverflow.com/users/708', 'pm_score': 7, 'selected': True, 'text': '<p>How about using LINQ To Objects to sort for you?</p>\n\n<p>Say you have a <code>IList&lt;Car&gt;</code>, and the car had an <code>Engine</code> property, I believe you could sort as follows:</p>\n\n<pre><code>from c in list\norderby c.Engine\nselect c;\n</code></pre>\n\n<p><em>Edit: You do need to be quick to get answers in here. As I presented a slightly different syntax to the other answers, I will leave my answer - however, the other answers presented are equally valid.</em></p>\n'}, {'answer_id': 15495, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 6, 'selected': False, 'text': '<p>You can use LINQ:</p>\n\n<pre><code>using System.Linq;\n\nIList&lt;Foo&gt; list = new List&lt;Foo&gt;();\nIEnumerable&lt;Foo&gt; sortedEnum = list.OrderBy(f=&gt;f.Bar);\nIList&lt;Foo&gt; sortedList = sortedEnum.ToList();\n</code></pre>\n'}, {'answer_id': 16025, 'author': 'ICR', 'author_id': 214, 'author_profile': 'https://Stackoverflow.com/users/214', 'pm_score': 0, 'selected': False, 'text': "<p>Here's an example using the stronger typing. Not sure if it's necessarily the best way though.</p>\n\n<pre><code>static void Main(string[] args)\n{\n    IList list = new List&lt;int&gt;() { 1, 3, 2, 5, 4, 6, 9, 8, 7 };\n    List&lt;int&gt; stronglyTypedList = new List&lt;int&gt;(Cast&lt;int&gt;(list));\n    stronglyTypedList.Sort();\n}\n\nprivate static IEnumerable&lt;T&gt; Cast&lt;T&gt;(IEnumerable list)\n{\n    foreach (T item in list)\n    {\n        yield return item;\n    }\n}\n</code></pre>\n\n<p>The Cast function is just a reimplementation of the extension method that comes with 3.5 written as a normal static method. It is quite ugly and verbose unfortunately.</p>\n"}, {'answer_id': 83241, 'author': 'Amy B', 'author_id': 8155, 'author_profile': 'https://Stackoverflow.com/users/8155', 'pm_score': 0, 'selected': False, 'text': '<p>In VS2008, when I click on the service reference and select "Configure Service Reference", there is an option to choose how the client de-serializes lists returned from the service.</p>\n\n<p>Notably, I can choose between System.Array, System.Collections.ArrayList and System.Collections.Generic.List</p>\n'}, {'answer_id': 512755, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Found a good post on this and thought I\'d share. <a href="http://foxsys.blogspot.com/search?q=IList+Sort" rel="nofollow noreferrer">Check it out HERE</a></p>\n\n<p>Basically.</p>\n\n<p>You can create the following class and IComparer Classes</p>\n\n<pre><code>public class Widget {\n    public string Name = string.Empty;\n    public int Size = 0;\n\n    public Widget(string name, int size) {\n    this.Name = name;\n    this.Size = size;\n}\n}\n\npublic class WidgetNameSorter : IComparer&lt;Widget&gt; {\n    public int Compare(Widget x, Widget y) {\n        return x.Name.CompareTo(y.Name);\n}\n}\n\npublic class WidgetSizeSorter : IComparer&lt;Widget&gt; {\n    public int Compare(Widget x, Widget y) {\n    return x.Size.CompareTo(y.Size);\n}\n}\n</code></pre>\n\n<p>Then If you have an IList, you can sort it like this.</p>\n\n<pre><code>List&lt;Widget&gt; widgets = new List&lt;Widget&gt;();\nwidgets.Add(new Widget("Zeta", 6));\nwidgets.Add(new Widget("Beta", 3));\nwidgets.Add(new Widget("Alpha", 9));\n\nwidgets.Sort(new WidgetNameSorter());\nwidgets.Sort(new WidgetSizeSorter());\n</code></pre>\n\n<p>But Checkout this site for more information... <a href="http://foxsys.blogspot.com/search?q=IList+Sort" rel="nofollow noreferrer">Check it out HERE</a></p>\n'}, {'answer_id': 1087089, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<pre><code>using System.Linq;\n\nvar yourList = SomeDAO.GetRandomThings();\nyourList.ToList().Sort( (thing, randomThing) =&gt; thing.CompareThisProperty.CompareTo( randomThing.CompareThisProperty ) );\n</code></pre>\n\n<p>That's pretty !ghetto.</p>\n"}, {'answer_id': 3242024, 'author': 'John', 'author_id': 239628, 'author_profile': 'https://Stackoverflow.com/users/239628', 'pm_score': 1, 'selected': False, 'text': "<p>Found this thread while I was looking for a solution to the exact problem described in the original post. None of the answers met my situation entirely, however. Brody's answer was pretty close. Here is my situation and solution I found to it.</p>\n\n<p>I have two ILists of the same type returned by NHibernate and have emerged the two IList into one, hence the need for sorting.</p>\n\n<p>Like Brody said I implemented an ICompare on the object (ReportFormat) which is the type of my IList:</p>\n\n<pre><code> public class FormatCcdeSorter:IComparer&lt;ReportFormat&gt;\n    {\n       public int Compare(ReportFormat x, ReportFormat y)\n        {\n           return x.FormatCode.CompareTo(y.FormatCode);\n        }\n    }\n</code></pre>\n\n<p>I then convert the merged IList to an array of the same type:</p>\n\n<pre><code>ReportFormat[] myReports = new ReportFormat[reports.Count]; //reports is the merged IList\n</code></pre>\n\n<p>Then sort the array: </p>\n\n<pre><code>Array.Sort(myReports, new FormatCodeSorter());//sorting using custom comparer\n</code></pre>\n\n<p>Since one-dimensional array implements the interface <code>System.Collections.Generic.IList&lt;T&gt;</code>, the array can be used just like the original IList.</p>\n"}, {'answer_id': 3691280, 'author': 'Yoav', 'author_id': 445117, 'author_profile': 'https://Stackoverflow.com/users/445117', 'pm_score': 0, 'selected': False, 'text': '<p>Is this a valid solution?</p>\n\n<pre><code>        IList&lt;string&gt; ilist = new List&lt;string&gt;();\n        ilist.Add("B");\n        ilist.Add("A");\n        ilist.Add("C");\n\n        Console.WriteLine("IList");\n        foreach (string val in ilist)\n            Console.WriteLine(val);\n        Console.WriteLine();\n\n        List&lt;string&gt; list = (List&lt;string&gt;)ilist;\n        list.Sort();\n        Console.WriteLine("List");\n        foreach (string val in list)\n            Console.WriteLine(val);\n        Console.WriteLine();\n\n        list = null;\n\n        Console.WriteLine("IList again");\n        foreach (string val in ilist)\n            Console.WriteLine(val);\n        Console.WriteLine();\n</code></pre>\n\n<p>The result was:\nIList\nB\nA\nC</p>\n\n<p>List\nA\nB\nC</p>\n\n<p>IList again\nA\nB\nC</p>\n'}, {'answer_id': 4388250, 'author': 'Bruno', 'author_id': 535044, 'author_profile': 'https://Stackoverflow.com/users/535044', 'pm_score': 1, 'selected': False, 'text': '<p>Useful for grid sorting this method sorts list based on property names. As follow the example.</p>\n\n<pre><code>    List&lt;MeuTeste&gt; temp = new List&lt;MeuTeste&gt;();\n\n    temp.Add(new MeuTeste(2, "ramster", DateTime.Now));\n    temp.Add(new MeuTeste(1, "ball", DateTime.Now));\n    temp.Add(new MeuTeste(8, "gimm", DateTime.Now));\n    temp.Add(new MeuTeste(3, "dies", DateTime.Now));\n    temp.Add(new MeuTeste(9, "random", DateTime.Now));\n    temp.Add(new MeuTeste(5, "call", DateTime.Now));\n    temp.Add(new MeuTeste(6, "simple", DateTime.Now));\n    temp.Add(new MeuTeste(7, "silver", DateTime.Now));\n    temp.Add(new MeuTeste(4, "inn", DateTime.Now));\n\n    SortList(ref temp, SortDirection.Ascending, "MyProperty");\n\n    private void SortList&lt;T&gt;(\n    ref List&lt;T&gt; lista\n    , SortDirection sort\n    , string propertyToOrder)\n    {\n        if (!string.IsNullOrEmpty(propertyToOrder)\n        &amp;&amp; lista != null\n        &amp;&amp; lista.Count &gt; 0)\n        {\n            Type t = lista[0].GetType();\n\n            if (sort == SortDirection.Ascending)\n            {\n                lista = lista.OrderBy(\n                    a =&gt; t.InvokeMember(\n                        propertyToOrder\n                        , System.Reflection.BindingFlags.GetProperty\n                        , null\n                        , a\n                        , null\n                    )\n                ).ToList();\n            }\n            else\n            {\n                lista = lista.OrderByDescending(\n                    a =&gt; t.InvokeMember(\n                        propertyToOrder\n                        , System.Reflection.BindingFlags.GetProperty\n                        , null\n                        , a\n                        , null\n                    )\n                ).ToList();\n            }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 5037815, 'author': 'David Mills', 'author_id': 29696, 'author_profile': 'https://Stackoverflow.com/users/29696', 'pm_score': 6, 'selected': False, 'text': '<p>This question inspired me to write a blog post: <a href="http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/" rel="noreferrer">http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/</a></p>\n\n<p>I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList&lt;T&gt;, but the next best thing is to create your own extension method. It\'s not too hard to create a couple of methods that will allow you to sort an IList&lt;T&gt; as you would a List&lt;T&gt;. As a bonus you can overload the LINQ OrderBy extension method using the same technique, so that whether you\'re using List.Sort, IList.Sort, or IEnumerable.OrderBy, you can use the exact same syntax.</p>\n\n<pre><code>public static class SortExtensions\n{\n    //  Sorts an IList&lt;T&gt; in place.\n    public static void Sort&lt;T&gt;(this IList&lt;T&gt; list, Comparison&lt;T&gt; comparison)\n    {\n        ArrayList.Adapter((IList)list).Sort(new ComparisonComparer&lt;T&gt;(comparison));\n    }\n\n    // Sorts in IList&lt;T&gt; in place, when T is IComparable&lt;T&gt;\n    public static void Sort&lt;T&gt;(this IList&lt;T&gt; list) where T: IComparable&lt;T&gt;\n    {\n        Comparison&lt;T&gt; comparison = (l, r) =&gt; l.CompareTo(r);\n        Sort(list, comparison);\n\n    }\n\n    // Convenience method on IEnumerable&lt;T&gt; to allow passing of a\n    // Comparison&lt;T&gt; delegate to the OrderBy method.\n    public static IEnumerable&lt;T&gt; OrderBy&lt;T&gt;(this IEnumerable&lt;T&gt; list, Comparison&lt;T&gt; comparison)\n    {\n        return list.OrderBy(t =&gt; t, new ComparisonComparer&lt;T&gt;(comparison));\n    }\n}\n\n// Wraps a generic Comparison&lt;T&gt; delegate in an IComparer to make it easy\n// to use a lambda expression for methods that take an IComparer or IComparer&lt;T&gt;\npublic class ComparisonComparer&lt;T&gt; : IComparer&lt;T&gt;, IComparer\n{\n    private readonly Comparison&lt;T&gt; _comparison;\n\n    public ComparisonComparer(Comparison&lt;T&gt; comparison)\n    {\n        _comparison = comparison;\n    }\n\n    public int Compare(T x, T y)\n    {\n        return _comparison(x, y);\n    }\n\n    public int Compare(object o1, object o2)\n    {\n        return _comparison((T)o1, (T)o2);\n    }\n}\n</code></pre>\n\n<p>With these extensions, sort your IList just like you would a List:</p>\n\n<pre><code>IList&lt;string&gt; iList = new []\n{\n    "Carlton", "Alison", "Bob", "Eric", "David"\n};\n\n// Use the custom extensions:\n\n// Sort in-place, by string length\niList.Sort((s1, s2) =&gt; s1.Length.CompareTo(s2.Length));\n\n// Or use OrderBy()\nIEnumerable&lt;string&gt; ordered = iList.OrderBy((s1, s2) =&gt; s1.Length.CompareTo(s2.Length));\n</code></pre>\n\n<p>There\'s more info in the post: <a href="http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/" rel="noreferrer">http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/</a></p>\n'}, {'answer_id': 12211204, 'author': 'Dhanasekar Murugesan', 'author_id': 1565396, 'author_profile': 'https://Stackoverflow.com/users/1565396', 'pm_score': 2, 'selected': False, 'text': '<pre><code>try this  **USE ORDER BY** :\n\n   public class Employee\n    {\n        public string Id { get; set; }\n        public string Name { get; set; }\n    }\n\n private static IList&lt;Employee&gt; GetItems()\n        {\n            List&lt;Employee&gt; lst = new List&lt;Employee&gt;();\n\n            lst.Add(new Employee { Id = "1", Name = "Emp1" });\n            lst.Add(new Employee { Id = "2", Name = "Emp2" });\n            lst.Add(new Employee { Id = "7", Name = "Emp7" });\n            lst.Add(new Employee { Id = "4", Name = "Emp4" });\n            lst.Add(new Employee { Id = "5", Name = "Emp5" });\n            lst.Add(new Employee { Id = "6", Name = "Emp6" });\n            lst.Add(new Employee { Id = "3", Name = "Emp3" });\n\n            return lst;\n        }\n\n**var lst = GetItems().AsEnumerable();\n\n            var orderedLst = lst.OrderBy(t =&gt; t.Id).ToList();\n\n            orderedLst.ForEach(emp =&gt; Console.WriteLine("Id - {0} Name -{1}", emp.Id, emp.Name));**\n</code></pre>\n'}, {'answer_id': 39031496, 'author': 'dana', 'author_id': 315689, 'author_profile': 'https://Stackoverflow.com/users/315689', 'pm_score': 3, 'selected': False, 'text': '<p>The accepted answer by @DavidMills is quite good, but I think it can be improved upon.  For one, there is no need to define the <code>ComparisonComparer&lt;T&gt;</code> class when the framework already includes a static method <code>Comparer&lt;T&gt;.Create(Comparison&lt;T&gt;)</code>.  This method can be used to create an <code>IComparison</code> on the fly.</p>\n<p>Also, it casts <code>IList&lt;T&gt;</code> to <code>IList</code> which has the potential to be dangerous.  In most cases that I have seen, <code>List&lt;T&gt;</code> which implements <code>IList</code> is used behind the scenes to implement <code>IList&lt;T&gt;</code>, but this is not guaranteed and can lead to brittle code.</p>\n<p>Lastly, the overloaded <code>List&lt;T&gt;.Sort()</code> method has 4 signatures and only 2 of them are implemented.</p>\n<ol>\n<li><code>List&lt;T&gt;.Sort()</code></li>\n<li><code>List&lt;T&gt;.Sort(Comparison&lt;T&gt;)</code></li>\n<li><code>List&lt;T&gt;.Sort(IComparer&lt;T&gt;)</code></li>\n<li><code>List&lt;T&gt;.Sort(Int32, Int32, IComparer&lt;T&gt;)</code></li>\n</ol>\n<p>The below class implements all 4 <code>List&lt;T&gt;.Sort()</code> signatures for the <code>IList&lt;T&gt;</code> interface:</p>\n<pre><code>using System;\nusing System.Collections.Generic;\n\npublic static class IListExtensions\n{\n    public static void Sort&lt;T&gt;(this IList&lt;T&gt; list)\n    {\n        if (list is List&lt;T&gt; listImpl)\n        {\n            listImpl.Sort();\n        }\n        else\n        {\n            var copy = new List&lt;T&gt;(list);\n            copy.Sort();\n            Copy(copy, 0, list, 0, list.Count);\n        }\n    }\n\n    public static void Sort&lt;T&gt;(this IList&lt;T&gt; list, Comparison&lt;T&gt; comparison)\n    {\n        if (list is List&lt;T&gt; listImpl)\n        {\n            listImpl.Sort(comparison);\n        }\n        else\n        {\n            var copy = new List&lt;T&gt;(list);\n            copy.Sort(comparison);\n            Copy(copy, 0, list, 0, list.Count);\n        }\n    }\n\n    public static void Sort&lt;T&gt;(this IList&lt;T&gt; list, IComparer&lt;T&gt; comparer)\n    {\n        if (list is List&lt;T&gt; listImpl)\n        {\n            listImpl.Sort(comparer);\n        }\n        else\n        {\n            var copy = new List&lt;T&gt;(list);\n            copy.Sort(comparer);\n            Copy(copy, 0, list, 0, list.Count);\n        }\n    }\n\n    public static void Sort&lt;T&gt;(this IList&lt;T&gt; list, int index, int count,\n        IComparer&lt;T&gt; comparer)\n    {\n        if (list is List&lt;T&gt; listImpl)\n        {\n            listImpl.Sort(index, count, comparer);\n        }\n        else\n        {\n            var range = new List&lt;T&gt;(count);\n            for (int i = 0; i &lt; count; i++)\n            {\n                range.Add(list[index + i]);\n            }\n            range.Sort(comparer);\n            Copy(range, 0, list, index, count);\n        }\n    }\n\n    private static void Copy&lt;T&gt;(IList&lt;T&gt; sourceList, int sourceIndex,\n        IList&lt;T&gt; destinationList, int destinationIndex, int count)\n    {\n        for (int i = 0; i &lt; count; i++)\n        {\n            destinationList[destinationIndex + i] = sourceList[sourceIndex + i];\n        }\n    }\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>class Foo\n{\n    public int Bar;\n\n    public Foo(int bar) { this.Bar = bar; }\n}\n\nvoid TestSort()\n{\n    IList&lt;int&gt; ints = new List&lt;int&gt;() { 1, 4, 5, 3, 2 };\n    IList&lt;Foo&gt; foos = new List&lt;Foo&gt;()\n    {\n        new Foo(1),\n        new Foo(4),\n        new Foo(5),\n        new Foo(3),\n        new Foo(2),\n    };\n\n    ints.Sort();\n    foos.Sort((x, y) =&gt; Comparer&lt;int&gt;.Default.Compare(x.Bar, y.Bar));\n}\n</code></pre>\n<p>The idea here is to leverage the functionality of the underlying <code>List&lt;T&gt;</code> to handle sorting whenever possible.  Again, most <code>IList&lt;T&gt;</code> implementations that I have seen use this.  In the case when the underlying collection is a different type, fallback to creating a new instance of <code>List&lt;T&gt;</code> with elements from the input list, use it to do the sorting, then copy the results back to the input list.  This will work even if the input list does not implement the <code>IList</code> interface.</p>\n'}, {'answer_id': 58669695, 'author': 'Momodu Deen Swarray', 'author_id': 10032850, 'author_profile': 'https://Stackoverflow.com/users/10032850', 'pm_score': 0, 'selected': False, 'text': '<p>This looks MUCH MORE SIMPLE if you ask me. This works PERFECTLY for me.</p>\n\n<p>You could use Cast() to change it to IList then use OrderBy():</p>\n\n<pre><code>    var ordered = theIList.Cast&lt;T&gt;().OrderBy(e =&gt; e);\n</code></pre>\n\n<p>WHERE T is the type eg. Model.Employee or Plugin.ContactService.Shared.Contact</p>\n\n<p>Then you can use a for loop and its DONE.</p>\n\n<pre><code>  ObservableCollection&lt;Plugin.ContactService.Shared.Contact&gt; ContactItems= new ObservableCollection&lt;Contact&gt;();\n\n    foreach (var item in ordered)\n    {\n       ContactItems.Add(item);\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/15486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/493/']