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

获得了具有Country属性和String属性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;}
}
上一篇:如何在PHP中结合两种排序方法?


下一篇:C#-需要更好的方法来将一个列表与另一个列表进行排序