C# doesn't allow lambda functions to represent iterator blocks (e.g., no "yield return" allowed inside a lambda function). If I wanted to create a lazy enumerable that yielded all the drives at the time of enumeration for example, I'd like to do something like
IEnumerable<DriveInfo> drives = {foreach (var drive in DriveInfo.GetDrives())
yield return drive;};
It took a while, but I figured out this as a way to get that functionality:
var drives = Enumerable.Range(0, 1).SelectMany(_ => DriveInfo.GetDrives());
Is there a more idiomatic way?
Why not write your own method, something like:
public static IEnumerable<T> GetLazily<T>(Func<IEnumerable<T>> getSource)
{
foreach (var t in getSource())
yield return t;
}
or:
public static IEnumerable<T> GetLazily<T>(Func<IEnumerable<T>> getSource)
{
return (new int[1]).SelectMany(_ => getSource());
}
It ought to allow usage like this:
var drives = GetLazily(DriveInfo.GetDrives);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With