I have a couple of classes that implement an interface, IFoo. I need to display a list of objects of these classes in a table, which I'd like to be able to sort by any arbitrary column in the table. So, the data source for the table is a List<IFoo>
.
The problem I've run into is that the standard way of implementing IComparable
or IComparer
for objects that are used in a list requires a static method, but static methods aren't allowed in interfaces. So, the question boils down to this: how does one sort a List<IFoo>
?
I am not sure what problem you are running into because I just ran a quick test and could sort a list of IFoo. See below for how I did this. If this does not fit your need, could you maybe give more detail?
Interface and Concrete
IComparable
I don't know what gives you the idea that you need to be using a static method, but it's not correct.
You can force all your
IFoo
implementers to implementIComparable<IFoo>
by adding it toIFoo
:Then simply sort your
List<IFoo>
like so:Sorting by an arbitrary column
You initially stated you want to sort by an arbitrary column in a table of IFoo objects. This is more complex; you need to be able to sort a list of objects by any one of their public properties, so the basic
IComparable<IFoo>
implementation above isn't going to cut it.The solution is to create a
PropertyComparer<T>
class which implementsIComparer<T>
, and will sort by any property ofT
. You could write it specifically forIFoo
, but at some point every developer tends to come up against this problem and ends up writing a generic property compararer that will try to sort any type. As a result you can google "c# property comparer" and you're sure to get several hits. Here's a simple one:http://www.codeproject.com/Articles/16200/Simple-PropertyComparer
If you are using C# 3/4, you can use a lambda expression..
This example shows how you can sort by different properties of the IFoo interface:
Output: