开发者

OrderBy, ObservableCollection<dynamic>, ICompare

开发者 https://www.devze.com 2023-04-10 11:12 出处:网络
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

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 DynamicSerializa开发者_高级运维bleComparer());

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

        }


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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消