gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:28:31 25 4
gpt4 key购买 nike

得到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com