有时检查不可重复 的内容是否有用,以查看IEnumerable它是否为空.LINQ Any对此不起作用,因为它消耗了序列的第一个元素,例如
if(input.Any())
{
foreach(int i in input)
{
// Will miss the first element for non-repeatable sequences!
}
}
Run Code Online (Sandbox Code Playgroud)
(注意:我知道在这种情况下没有必要进行检查 - 这只是一个例子!真实世界的例子是Zip对一个IEnumerable可能是空的右手执行.如果它是空的,我想要结果是左手IEnumerable原样.)
我想出了一个看起来像这样的潜在解决方案:
private static IEnumerable<T> NullifyIfEmptyHelper<T>(IEnumerator<T> e)
{
using(e)
{
do
{
yield return e.Current;
} while (e.MoveNext());
}
}
public static IEnumerable<T> NullifyIfEmpty<T>(this IEnumerable<T> source)
{
IEnumerator<T> e = source.GetEnumerator();
if(e.MoveNext())
{
return NullifyIfEmptyHelper(e);
}
else
{
e.Dispose();
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以按如下方式使用:
input = input.NullifyIfEmpty(); …Run Code Online (Sandbox Code Playgroud)