【问题标题】:Using Linq IQueryable, set which field to filter on depending on another field in the same table使用 Linq IQueryable,根据同一张表中的另一个字段设置过滤哪个字段
【发布时间】:2021-03-03 07:42:57
【问题描述】:

我有一个包含三个字段的汽车表。 我需要根据第三个字段的值过滤两个字段之一。 如果车辆被标记为“Special”,则过滤 SpecialPrice 字段,否则过滤“NormalPrice”字段。 我需要帮助的是如何编写 Linq 查询以根据特殊布尔字段值决定过滤哪个字段。

示例表:汽车

Special: bool

SpecialPrice: int

NormalPrice: int

IQueryable<Car> query = _context.Car;

if (Special)
 query = query.Where(x => x.SpecialPrice <= 100);
else
 query = query.Where(x => x.NormalPrice <= 100);

【问题讨论】:

    标签: c# linq filter


    【解决方案1】:
    query = query.Where(x => x.Special == true ? x.SpecialPrice <= 100 : x.NormalPrice <= 100);
    

    【讨论】:

      【解决方案2】:

      一旦你明确了你的要求,查询就会很简单。

      要求:所以您有一个价格价值,并且您只想要具有以下条件的汽车:

      car.Special AND car.SpecialPrice == price
      OR
      not car.Special AND car.NormalPrice == price
      

      查询:

      decimal price = 100;
      var result = dbContext.Cars.Where(car =>
      
          (car.Special && car.SpecialPrice == price)
       || (!car.Special && car.NormalPrice == price));
      

      简单的祝你好运!

      【讨论】:

        猜你喜欢
        • 2022-07-20
        • 2019-03-22
        • 2016-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多