【问题标题】:Is there a Lambda Else condition?是否存在 Lambda Else 条件?
【发布时间】:2013-07-18 02:19:44
【问题描述】:

我正在使用 lambda 语句来设置我的 foreach 循环:

foreach (Shape shape in shapefile.Where(x=>x.GetMetadata(IgnoreField) != IgnoreValue))

IgnoreFieldIgnoreValue可选参数。

如果这些字段为空白(未使用),我该如何更改我的 foreach 来解决这个问题?是否有 Else 声明或类似的声明?

【问题讨论】:

    标签: c# .net linq foreach lambda


    【解决方案1】:

    我认为你想要的是......如果它们不为空......然后检查它们......但如果它们为空那么忽略它们对吗?

    foreach (Shape shape in shapefile.Where(x=>
       x.IgnoreField == null ||
       x.IgnoreValue == null ||
       x.GetMetadata(IgnoreField) != IgnoreValue)
    

    还请注意,当您缩进 LinQ 时,更容易看到它在做什么?

    我使用的另一种格式化技术,尤其是在像这样的 foreach 语句中,是在像这样在 foreach 语句中使用它之前将可枚举存储在一个适当命名的变量中......

    var shapesFilteredByIgnores = shapefile.Where(x=>
       x.IgnoreField == null ||
       x.IgnoreValue == null ||
       x.GetMetadata(IgnoreField) != IgnoreValue)
    
    foreach (Shape shape in shapesFilteredByIgnores)
    

    当然,这只有在你有一个有意义的变量名来分配时才会更清楚。

    【讨论】:

    • 我认为第二个null 检查是不必要的,因为如果其中一个是null,你就无法做到这一点。
    【解决方案2】:

    这不是魔法。完全使用您在 lambda 之外使用的内容:

    foreach (Shape shape in shapefile.Where(x=>
       (x.IgnoreField != null && // If both optional fields are present
       x.IgnoreValue != null &&
       x.GetMetadata(IgnoreField) != IgnoreValue) // Then only where metadata for 
                                                  // ignored field is not the ignored value
       ||
       (x.IgnoreField == null || x.IgnoreValue == null))) // But if either field absent
                                                          // then return all data
    

    【讨论】:

    • 这对我来说似乎不是可选的......我没有得到什么?
    • 如果两个可选字段之一不存在,OP 没有说明他想要检索哪些数据。当可选字段之一不存在时,我会将其更改为返回所有行。
    • IgnoreField 和 IgnoreValue 不是 shapefile 的一部分,它们是通过 ini 文件填充的真正全局变量。我对此不够清楚。所以我想我可以使用 || 中的所有内容部分。
    【解决方案3】:
    foreach (Shape shape in shapefile.Where(x=>IgnoreField==null || IngoreValue==null || x.GetMetadata(IgnoreField) != IgnoreValue))
    

    【讨论】:

    • 我该如何解释它是如何工作的?这看起来就像我正在寻找的答案,我只是想要能够解释它,以便我以后可以在笔记中提醒自己。
    • 这个表达式和你的一样,有两个额外的条件来检查全局 IgnoreField 和 IgnoreValue 参数是否为空。因此,如果这些参数中的任何一个为空,则将检索所有项目。如果两者都不为null,则所有项目都将被条件过滤。
    • 由于IgnoreFieldIngoreValue 在迭代过程中不会改变,最好在迭代之前检查它们,而不是检查shapefile 中的每个值。
    【解决方案4】:

    您可以根据是否有要检查的值有条件地应用Where

    var query = shapefile.AsEnumerable();
    
    if(IgnoreField!=null && IngoreValue!=null)
        query = query.Where(x=>x.GetMetadata(IgnoreField) != IgnoreValue);
    
    foreach (Shape shape in query)
        {...}
    

    与此处的其他答案不同,这不会为序列中的每个项目检查null 的两个字段;它会检查它们一次,并仅在可能的情况下应用过滤器。

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2011-03-24
      • 1970-01-01
      相关资源
      最近更新 更多