无法为订购LINQ查询创建Func表达式

use*_*388 1 c# linq func

我从我的请求中收到此参数:

sort=homeCountry
Run Code Online (Sandbox Code Playgroud)

我需要按照发送到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
);
Run Code Online (Sandbox Code Playgroud)

这工作正常.

但是,上面的列都是字符串.但是,我还需要添加十进制列,如下所示:

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
);
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误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; }       

}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ish 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);

        //....
    }
}
Run Code Online (Sandbox Code Playgroud)