【问题标题】:C# list min and max rangeC# 列出最小和最大范围
【发布时间】:2019-06-30 01:50:12
【问题描述】:

我有一个有价格的属性对象列表。我希望列表在一定的价格范围内。

例如

最高价格:800000 最低价格:200000

results = props.results.Where(x => x.PropertyType.ToLower() != propertytype.ToLower()   && (x.Price >= minPrice && x.Price <= maxPrice)).OrderByDescending(x => Math.Abs(x.Price - price));

代码运行良好。有没有更好的方法?

【问题讨论】:

  • Better way 是什么意思?是表演还是写作?
  • 只是语法
  • 刚刚看到一些反对票。不知道为什么

标签: c# list linq c#-4.0 range


【解决方案1】:

您的范围条件看起来不对,应该是 x.Price &gt;= minPrice &amp;&amp; x.Price &lt;= maxPrice,如果您正在寻找类似 SQL between 的语法,那么不,不存在这样的结构

【讨论】:

    【解决方案2】:

    你的代码很好。

    如果您愿意,您可以为int(或您使用的任何数据类型)创建一个扩展方法:

    public static class Extensions
    {
        public static bool IsBetween(this int value, int min, int max)
        {
            return value >= min && value <= max;
        }
    }
    

    并将其称为

    integers.Where(x => x.IsBetween(3, 5))
    

    【讨论】:

      【解决方案3】:

      您可以尝试以更复杂的方式编写查询,例如,

      results = props.results.Where(x => x.PropertyType.ToLower() != propertytype.ToLower())
                             .Where(y => y.Price >= minPrice && y.Price <= maxPrice)
                             .OrderByDescending(z => Math.Abs(z.Price - price));
      

      【讨论】:

        猜你喜欢
        • 2014-03-22
        • 2020-08-27
        • 2015-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多