我替换了以下代码
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)
答案 0 :(得分:2)
没有像这样的标准扩展,很可能是因为返回/传递null枚举被认为是一种不好的做法。
在C#6 (VS2015)中,您可以使用以下糖
var q = myEnumerable?
.Where(o => o.Somehing == something)
.Select(o => o.SomeOtherThing);
但请注意,在这种情况下,结果q
将为null
,而在您的数据中为空可枚举。
修改由于您编辑了问题并添加了其他约束,请忘记?.
运算符 - 它无论如何都不会产生相同的结果(正如我所提到的)。但这并没有改变开头的主要答案
不是像这样的标准扩展