是否存在Lambda Else条件?

时间:2013-07-18 22:40:06

标签: c# .net linq foreach lambda

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

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

IgnoreFieldIgnoreValue可选参数。

如果这些字段是空白的(未使用),我怎么能改变我的foreach来解释这个?有没有Else声明或类似的东西?

4 个答案:

答案 0 :(得分:4)

我认为你想要的是......如果它们不是空的......那么检查它们......但是如果它们是null,那么忽略它们吧?

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

还要注意当你缩进你的LinQ时,如何更容易看到它在做什么?

我使用的另一种格式化技术,特别是对于这样的foreach语句,是在将foreumerable在foreach语句中使用之前将其存储在适当命名的变量中,如此...

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

foreach (Shape shape in shapesFilteredByIgnores)

当然,如果你有一个有意义的变量名称来分配它,那就更清楚了。

答案 1 :(得分:3)

这不是魔术。准确使用你在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

答案 2 :(得分:2)

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

答案 3 :(得分:2)

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

var query = shapefile.AsEnumerable();

if(IgnoreField!=null && IngoreValue!=null)
    query = query.Where(x=>x.GetMetadata(IgnoreField) != IgnoreValue);

foreach (Shape shape in query)
    {...}

与此处的其他答案不同,这并不需要为序列中的每个项检查null的两个字段;它会检查一次,只有在能够使用时才应用过滤器。

相关问题