Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an IEnumerable<> from a generator method using a factory function

Tags:

c#

linq

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);
}
like image 949
Mahmoud Samy Avatar asked Dec 19 '16 15:12

Mahmoud Samy


1 Answers

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.

like image 72
Jeroen van Langen Avatar answered Nov 12 '22 16:11

Jeroen van Langen