开发者

Dynamic collection generation with linq

I wonder if linq already contains somet开发者_运维知识库hing to generate collections on the fly.

Lets say i want a dynamic collection of GUIDs, I currently use something like the following code for it:

public static IEnumerable<T> Generate<T>(Func<T> generator)
{
    for (;;)
    {
        yield return generator();
    }
}

var someIds = MyLinqExtensions.Generate(Guid.NewGuid).Take(10);

As such a construct is really handy sometimes, I'd rather not re-implement the wheel if such thing exists already.


You could use Range to generate a sequence of ints an then use Select to instantiate the item:

Enumerable.Range(1, 10).Select(i => Guid.NewGuid());


No, I don't believe LINQ contains anything like that at the moment. The closest you could come would be:

var someIds = Enumerable.Repeat(0, int.MaxValue)
                        .Select(ignored => Guid.NewGuid)
                        .Take(10);


You might want to look at the InteractiveExtensions (IX) from the same people that brought you LINQ and RX. Among other things, it includes a Generate method similar to what you are proposing:

public static IEnumerable Generate(TState initialState, Func condition, Func iterate, Func resultSelector)

I did a brief writeup of IX at http://www.thinqlinq.com/Post.aspx/Title/Ix-Interactive-Extensions-return

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜