I have a factory function, and want to use it to create an Enumerable. In C# I didn't find a straight-forward declarative way to do the job. So I did it like this:
public IEnumerable<Contact> Get()
{
return Enumerable.Range(1, 5).Select(x => GenerateRandomContact());
}
Is there any better way?
// Expected format
public IEnumerable<Contact> Get()
{
return Enumerable.Generate(GenerateRandomContact).Take(5);
}
Something like:
public static IEnumerable<T> Generate(Func<T> generator)
{
while(true)
yield return generator.Invoke();
}
But you can't extend static classes. So you should place it in a helper class.
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