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>
?
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 implement IComparable<IFoo>
by adding it to IFoo
:
interface IFoo : IComparable<IFoo>
{
int Value { get; set; } // for example's sake
}
class SomeFoo : IFoo
{
public int Value { get; set; }
public int CompareTo(IFoo other)
{
// implement your custom comparison here...
return Value.CompareTo(other.Value); // e.g.
}
}
Then simply sort your List<IFoo>
like so:
list.Sort();
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 implements IComparer<T>
, and will sort by any property of T
. You could write it specifically for IFoo
, 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With