如何创建一个IEnumerable来在一个语句中懒惰地获取所有X.

Dax*_*ohl 6 c# lambda iterator lazy-evaluation

C#不允许lambda函数表示迭代器块(例如,lambda函数内不允许"yield return").如果我想创建一个懒惰的枚举,例如在枚举时产生所有驱动器,我想做类似的事情

IEnumerable<DriveInfo> drives = {foreach (var drive in DriveInfo.GetDrives()) 
                                     yield return drive;};
Run Code Online (Sandbox Code Playgroud)

花了一段时间,但我认为这是获得该功能的一种方式:

var drives = Enumerable.Range(0, 1).SelectMany(_ => DriveInfo.GetDrives());
Run Code Online (Sandbox Code Playgroud)

有更惯用的方式吗?

Jep*_*sen 1

为什么不编写自己的方法,例如:

public static IEnumerable<T> GetLazily<T>(Func<IEnumerable<T>> getSource)
{
  foreach (var t in getSource())
    yield return t;
}
Run Code Online (Sandbox Code Playgroud)

或者:

public static IEnumerable<T> GetLazily<T>(Func<IEnumerable<T>> getSource)
{
  return (new int[1]).SelectMany(_ => getSource());
}
Run Code Online (Sandbox Code Playgroud)

它应该允许这样的使用:

var drives = GetLazily(DriveInfo.GetDrives);
Run Code Online (Sandbox Code Playgroud)