IEnumerable T空合并扩展 [英] IEnumerable<T> null coalescing Extension
问题描述
在通过foreach或LINQ查询遍历IEnumerable<T>
之前,我经常遇到检查IEnumerable<T>
是否为空的问题,然后我经常遇到这样的代码:
I frequently face the problem to check whether an IEnumerable<T>
is null before iterating over it through foreach or LINQ queries, then I often come into codes like this:
var myProjection = (myList ?? Enumerable.Empty<T>()).Select(x => x.Foo)...
因此,我想将此扩展方法添加到Extensions类:
Hence, I thought to add this extension-method to an Extensions class:
public static class MyExtensions
{
public static IEnumerable<T> AsEmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
}
我很快就想到了一个小问题,即考虑到扩展方法的实例方法方面" ,应该将其实现为纯粹的静态方法,否则这样完全合法:
A little issue comes immediately in my mind looking at this code, i.e., given the "instance-methods aspect" of extension-methods, it should be implemented as a mere static method, otherwise something like this would be perfectly legal:
IEnumerable<int> list = null;
list.AsEmptyIfNull();
使用它是否还有其他缺点?
如果大量使用,这种扩展会导致开发人员出现某种不良趋势吗?
Do you see any other drawback in using it ?
Can such extension leading to some kind of bad-trend in the developer(s), if massively used?
奖励问题:
您能建议一个更好的名字吗? :)
(英语不是我的母语,所以我的名字不太好...)
Can you suggest a better name to it ? :)
(English is not my first language, then I'm not so good in naming...)
谢谢.
推荐答案
返回IEnumerable<T>
的方法应返回一个空值,而不是null.这样您就不需要了.
Methods that return an IEnumerable<T>
should return an empty one, instead of null. So you wouldn't need this.
查看此问题:返回null还是返回更好?空集合?
否则,您的代码就可以了.
Otherwise, your code seems ok.
这篇关于IEnumerable T空合并扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!