OrderBy,ObservableCollection <dynamic>,ICompare </dynamic>

时间:2011-10-04 21:00:46

标签: c# .net

我正在尝试对一组Observable动态对象进行排序。我尝试实现IComparer,但它告诉我,我无法实现动态接口。我现在被困住了。任何想法如何实现这个?

我试过这个

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

然后是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);
            }

        }

1 个答案:

答案 0 :(得分:0)

IComparer<dynamic>在编译时与IComparer<object>相同。 That's why you can't implement it.

尝试实施IComparer<object>,然后转换为动态。

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);
    }

}