我从我的请求中收到此参数:
sort=homeCountry
我需要按照发送到sort
参数的任何列进行排序,因此我创建了一个类似的方法:
string sort = "homeCountry";
Func<PaymentRateTrip, string> orderBy = (
x => sort == "homeCountry" ? x.HomeCountry :
sort == "hostCountry" ? x.HostCountry :
sort == "homeLocation" ? x.HomeLocation :
sort == "hostLocation" ? x.HostLocation :
x.HomeLocation
);
这是正常的。
但是,上面的列都是字符串。但是,我还需要添加十进制列,如下所示:
string sort = "homeCountry";
Func<PaymentRateTrip, string> orderBy = (
x => sort == "homeCountry" ? x.HomeCountry :
sort == "hostCountry" ? x.HostCountry :
sort == "homeLocation" ? x.HomeLocation :
sort == "hostLocation" ? x.HostLocation :
sort == "oneWayRate" ? x.oneWayRate :
x.HomeLocation
);
它在x.HostLocation
上显示错误:
由于存在,因此无法确定条件表达式的类型 'string'和'decimal?'之间没有隐式转换。
有没有更好的方法来做我想做的事情?我在寻找:
修改:PaymentRateTrip.cs
public class PaymentRateTrip
{
public Guid? Id { get; set; }
public Guid HomeCountryId { get; set; }
public string HomeCountry { get; set; }
public Guid HomeLocationId { get; set; }
public string HomeLocation { get; set; }
public Guid? HostCountryId { get; set; }
public string HostCountry { get; set; }
public Guid? HostLocationId { get; set; }
public string HostLocation { get; set; }
public decimal? OneWayRate { get; set; }
public decimal? RoundTripRate { get; set; }
public Guid? OneWayCurrencyId { get; set; }
public Guid? RoundTripCurrencyId { get; set; }
}
答案 0 :(得分:7)
我只是制作一个扩展方法:
public static IEnumerable<PaymentRateTrip> Sort(this IEnumerable<PaymentRateTrip> list, string sort)
{
switch (sort)
{
case "homeCountry":
return list.OrderBy(x => x.Whatever);
case "somethingElse":
return list.OrderBy(x => x.Whatever);
//....
}
}
答案 1 :(得分:1)
这似乎很简单但只是这样做
var prop = typeof(PaymentRateTrip).GetProperty(sort);
var ordered = lst.OrderBy(p => prop.GetValue(p));
只要排序名称是对象的一部分,就可以正常工作。 在您的情况下,函数是(p =&gt; prop.GetValue(p))