Sort the list of interface objects

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 that I would like to sort by any arbitrary column in the table. Thus, the data source for the table is List<IFoo>.

The problem I ran into is that the standard way to implement IComparableeither IComparerfor objects that are used in a list requires a static method, but static methods are not allowed in interfaces. So, the question boils down to the following: how to sort a List<IFoo>?

+2
source share
3 answers

Icomparable

, , , .

IFoo IComparable<IFoo>, IFoo:

interface IFoo : IComparable<IFoo> 
{ 
    int Value { get; set; } // for example 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.
    }
}

List<IFoo> :

list.Sort();

, IFoo. ; , IComparable<IFoo> .

PropertyComparer<T>, IComparer<T>, T. IFoo, - , , . google "# property comparer", . :

http://www.codeproject.com/Articles/16200/Simple-PropertyComparer

+7

, , , IFoo. . , . , ?

var fooList = new List<IFoo>{new testFoo{key=3}, new testFoo{key=1}};
fooList.Sort(
    delegate(IFoo obj1, IFoo obj2){return obj1.key.CompareTo(obj2.key);});

public interface IFoo
{
     int key{get;set;}
}

public class testFoo:IFoo
{
    public int key {get;set;}
}
+3

If you use C # 3/4, you can use the lambda expression ..

This example shows how you can sort by various IFoo interface properties:

void Main()
{
    List<IFoo> foos = new List<IFoo>
    {
        new Bar2{ Name = "Pqr", Price = 789.15m, SomeNumber = 3 },
        new Bar2{ Name = "Jkl", Price = 444.25m, SomeNumber = 1 },
        new Bar1{ Name = "Def", Price = 222.5m, SomeDate = DateTime.Now },
        new Bar1{ Name = "Ghi", Price = 111.1m, SomeDate = DateTime.Now },
        new Bar1{ Name = "Abc", Price = 123.45m, SomeDate = DateTime.Now },
        new Bar2{ Name = "Mno", Price = 564.33m, SomeNumber = 2 }

    };

    foos.Sort((x,y) => x.Name.CompareTo(y.Name));
    foreach(IFoo foo in foos)
    {
        Console.WriteLine(foo.Name);
    }

    foos.Sort((x,y) => x.Price.CompareTo(y.Price));
    foreach(IFoo foo in foos)
    {
        Console.WriteLine(foo.Price);
    }
}

interface IFoo
{
    string Name { get; set; }
    decimal Price { get; set; }
}

class Bar1 : IFoo
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public DateTime SomeDate { get; set; }
}

class Bar2 : IFoo
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int SomeNumber { get; set; }
}

Conclusion:

Abc
Def
Ghi
Jkl
Mno
Pqr
111.1
222.5
333.33
444.25
555.45
666.15
0
source

All Articles