2

I'm trying to sort an Observable collection of dynamic objects. I tried implementing IComparer but it tells me that I cannot implement a dynamic interface. I'm stuck now. Any ideas how to acomplish this?

I tried this

list.OrderByDescending(x => x, new DynamicSerializableComparer());

and then the IComparer

public class DynamicSerializableComparer : IComparer<dynamic>
        {
            string _property;

            public DynamicSerializableComparer(string property)
            {
                _property = property;
            }

            public int Compare(dynamic stringA, dynamic stringB)
            {
                string valueA = stringA.GetType().GetProperty(_property).GetValue();
                string valueB = stringB.GetType().GetProperty(_property).GetValue();

                return String.Compare(valueA, valueB);
            }

        }
Carlos Blanco
  • 8,592
  • 17
  • 71
  • 101

1 Answers1

0

IComparer<dynamic> is, at compile time, the same as IComparer<object>. That's why you can't implement it.

Try implementing IComparer<object> instead, and casting to dynamic.

public class DynamicSerializableComparer : IComparer<object>
{
    string _property;

    public DynamicSerializableComparer(string property)
    {
        _property = property;
    }

    public int Compare(object stringA, object stringB)
    {
        string valueA = stringA.GetType().GetProperty(_property).GetValue();
        string valueB = stringB.GetType().GetProperty(_property).GetValue();

        return String.Compare(valueA, valueB);
    }

}
svick
  • 236,525
  • 50
  • 385
  • 514
Jeff
  • 35,755
  • 15
  • 108
  • 220
  • 1
    This implementation won't work if the objects are actually dynamic (like `ExpandoObject` or some object coming from IronPython). – svick Oct 04 '11 at 22:30
  • Because `Type.GetProperty()` won't give you dynamic properties. `Type` doesn't know anything about `dynamic` or DLR (I think). – svick Oct 04 '11 at 22:36
  • @Svick: I don't think you're right. See http://stackoverflow.com/questions/4939508/get-value-of-c-dynamic-property-via-string – Eric J. Oct 04 '11 at 23:01
  • @EricJ., that question is about anonymous objects, which are not dynamic. It really doesn't work with types like `ExpandoObject`. – svick Oct 04 '11 at 23:05
  • In addition to svick's comment: how should IComparer be able to compare a dynamic, when a dynamic can be nearly anything – Michael Olesen Oct 04 '11 at 23:11
  • @Michael9000: Because it's using reflection. You can't do it with ExpandoObject, because it's a DynamicObject itself... – Jeff Oct 05 '11 at 14:09