简体   繁体   English

不了解LINQ查询

[英]Not understanding LINQ query

I am maintaining a project and have come across some code which I can't understand. 我正在维护一个项目并遇到了一些我无法理解的代码。 LINQ query: LINQ查询:

var toDraw = from tile in testArr.AsEnumerable()
             where tile.Item_Business_Unit != null ? 
             ((tile.Ending_Date >= DateTime.Now || tile.Ending_Date == DateTime.MinValue) && 
             ((tile.Sales_Code == null) || (tile.Sales_Code.ToString() == customerNumber) || 
             (tile.Sales_Code.ToString() == cpg)) && (tile.Unit_Price != 0)) : 
             ((tile.Ending_Date >= DateTime.Now || tile.Ending_Date == DateTime.MinValue) && 
             ((tile.Sales_Code == null) || (tile.Sales_Code.ToString() == customerNumber) || 
             (tile.Sales_Code.ToString() == cpg)) && (tile.Unit_Price != 0))
                             select tile;

From what I understand, from an array a tile is being selected which has the following criteria: 根据我的理解,从数组中选择一个具有以下标准的图块:

  • Ending date can be datetime.now or datetime.minvalue 结束日期可以是datetime.nowdatetime.minvalue
  • Sales code can be null or can be equal to customer no or cpg 销售代码可以为null,也可以等于customer no或cpg
  • Unit price should be greater than 0 单价应大于0

But I am not understanding why there is a conditional expression after tile.Item_Business_Unit since both of the conditions perform the same thing. 但我不明白为什么在tile.Item_Business_Unit之后存在条件表达式,因为两个条件执行相同的操作。 So will the item be selected even if it has a null business unit? 即使它有一个空业务单位,项目也会被选中吗? And does this work different from normal if/else operations? 这是否与正常的if / else操作不同?

Any suggestions would be very appreciated. 任何建议将非常感激。

Are you being thrown by the shortcut notation? 您是否被快捷方式符号抛出?

x = (test_case) ? (true_part) : (false_part);

If test_case evaluates to true , you would have 如果test_case计算结果为true ,那么就可以了

true_part

Whereas if test_case evaluates to false , this expression would be evaluated 而如果test_case计算结果为falsetest_case评估此表达式

false_part

UPDATE: 更新:

As an FYI: The resulting test of both sides of that conditional expression above are equal, so that cryptic code is not even necessary. 作为一个FYI:上面条件表达式双方的结果测试是相同的,因此甚至不需要神秘的代码。

You could replace that with this: 你可以用这个代替:

var toDraw = from tile in testArr.AsEnumerable()
    where 
    ((tile.Ending_Date >= DateTime.Now || tile.Ending_Date == DateTime.MinValue) &&
    ((tile.Sales_Code == null) || (tile.Sales_Code.ToString() == customerNumber) || (tile.Sales_Code.ToString() == cpg)) &&
    (tile.Unit_Price != 0)) 
    select tile;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM