代码之家  ›  专栏  ›  技术社区  ›  user1477388

无法创建用于排序LINQ查询的Func表达式

  •  1
  • user1477388  · 技术社区  · 12 年前

    我从请求中收到此参数:

    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?”之间没有隐式转换

    有没有更好的方法来做我想做的事?我正在寻找:

    • 一种可行的方法。
    • 一种可读的方式(类似于开关盒)。

    编辑: 付款率三分之一秒

    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; }       
    
    }
    
    2 回复  |  直到 12 年前
        1
  •  7
  •   Dave Bish    12 年前

    我只是做一个扩展方法:

    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);
    
            //....
        }
    }
    
        2
  •  1
  •   Pedro.The.Kid    12 年前

    这看起来很简单,但就这么做吧

            var prop = typeof(PaymentRateTrip).GetProperty(sort);
            var ordered = lst.OrderBy(p => prop.GetValue(p));
    

    只要排序名称是对象的一部分,这种方法就有效。 在您的情况下,函数为(p=>prop.GetValue(p))