是否存在可枚举的任何预先存在的扩展,使其NullReferenceException安全?

时间:2015-08-22 17:10:59

标签: c# linq

我替换了以下代码

if (myEnumerable != null)
{
 myEnumerable
   .Where(o => o.Somehing == something)
   .Select(o => o.SomeOtherThing);
}

使用

myEnumerable
 .EmptyIfNull()
 .Where(o => o.Somehing == something)
 .Select(o => o.SomeOtherThing);

但上述情况才有可能,因为我推出了自己的EmptyIfNull

public static IEnumerable<TElement> EmptyIfNull<TElement>(IEnumerable<TElement source)
{
 return source ?? Enumerable.Empty<TElement>();
}

我的问题是,是不是已经用LINQ扩展编写了类似于语法糖的东西? (不使用C#6.0)

1 个答案:

答案 0 :(得分:2)

没有像这样的标准扩展,很可能是因为返回/传递null枚举被认为是一种不好的做法。
C#6 (VS2015)中,您可以使用以下糖

var q = myEnumerable?
 .Where(o => o.Somehing == something)
 .Select(o => o.SomeOtherThing);

但请注意,在这种情况下,结果q将为null,而在您的数据中为空可枚举。

修改由于您编辑了问题并添加了其他约束,请忘记?.运算符 - 它无论如何都不会产生相同的结果(正如我所提到的)。但这并没有改变开头的主要答案

  

不是像这样的标准扩展