OrderBy, ObservableCollection<dynamic>, ICompare
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);
}
}
精彩评论