c# - OrderBy、ObservableCollection<动态>、ICompare

标签 c# .net

我正在尝试对动态对象的 Observable 集合进行排序。我尝试实现 IComparer,但它告诉我无法实现动态接口(interface)。我现在卡住了。有什么想法可以实现吗?

我试过了

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

        }

最佳答案

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

}

关于c# - OrderBy、ObservableCollection<动态>、ICompare,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7653969/

相关文章:

c# - 为什么 if 语句中的这个字符串初始化会阻止我打印?

c# - 如何创建一个临时表并在与 Entity Framework 的相同连接中使用它?

c# - 将转换器从 dll 导入 XAML

c# - 使用 NLog 通过 WebService 记录自定义类

c# - 在 C# 中替代 Session 变量,我们可以使用类及其对象来存储值而不是 session 变量吗?

.net - 无法打开 .NET winforms 应用程序来打开 CHM 文件中的帮助主题

c# - StringBuilder 真的比连接一打字符串慢吗?

c# - 将 MVC 4 升级到 MVC 5 连接问题

c# - 未知数量类型参数的类设计

c# - 未为加载的控件生成 ASP.NET 客户端 ID