c# - 通过反射按自定义属性对实体进行 Linq 排序

标签 c# linq sorting reflection

得到 Customer类有 Country具有字符串属性的属性 Name . 还有 Customer工具 IComparable<Country>像这样:

public int CompareTo(Country other)
{
    return string.Compare(this.Name, other.Name);
}

现在:

var custList = new List<Customer>{...};

custList.OrderBy(cust => cust.Country).ToList(); //Sorts as charm.

如果尝试通过反射排序:

var itemProp = typeof(Customer).GetProperty("Country");

custList = c.Customers.ToList()
    .OrderBy(cust => itemProp.GetValue(cust, null)).ToList(); // Fails

抛出异常'至少一个对象必须实现 IComparable'

请解释失败的原因以及如何通过反射正确地按自定义属性对客户进行排序。谢谢。

最佳答案

由于 GetValue 返回 Object,您需要实现 IComparable 的非泛型版本。

void Main()
{
    var custList = new List<Customer>()
    { 
        new Customer(){ Country = new Country(){ Name = "Sweden" } },
        new Customer(){ Country = new Country(){ Name = "Denmark" } },
    };

    var itemProp = typeof(Customer).GetProperty("Country");

    custList = custList.OrderBy(cust => itemProp.GetValue(cust, null)).ToList();

    custList.Dump();
}

public class Country : IComparable<Country>, IComparable
{
    public string Name {get;set;}

    public int CompareTo(Country other)
    {
        return string.Compare(this.Name, other.Name);
    }

    public int CompareTo(object other)
    {
        var o = other as Country;
        if(o == null)
            return 0; //Or how you want to handle it
        return CompareTo(o);
    }
}

public class Customer
{
    public Country Country{get;set;}
}

关于c# - 通过反射按自定义属性对实体进行 Linq 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719973/

相关文章:

c# - 在 VS2017 中将依赖程序集包含到 NuGet 包中

c# - 如何将 LINQ 结果传递给方法?

java - 基于 Java 标准的排序(自定义排序)

c# - 将方法移到另一个类时无法产生声音

c# - 如何使用 stackexchange.redis 从多个键中获取所有哈希元素

vb.net - 如何在 Linq to XML 中获取 XElement 的 .InnerText 值?

objective-c - 排序包含自定义对象的NSArray

c# - 如何在拆分字符串时对 List<LabelItem> 进行排序?

c# - 如何确定本地主机的 IPv4 地址?

c# - LINQ 查询返回每个类别中价格最高的项目