Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an IList in C#

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.

Turns out the IList interface doesn't have a sort method built in.

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

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.

So my question is, does anyone have an elegant solution to sorting an IList

like image 350
lomaxx Avatar asked Aug 19 '08 01:08

lomaxx


People also ask

What is IList in C sharp?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.


1 Answers

You can use LINQ:

using System.Linq;  IList<Foo> list = new List<Foo>(); IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar); IList<Foo> sortedList = sortedEnum.ToList(); 
like image 86
Mark Cidade Avatar answered Sep 22 '22 13:09

Mark Cidade