3

I wasn't really sure how to address this question, so I will start with "pseudo" code:

List<Player> players = new List<Player>();
players.Add(p1);
players.Add(p2);
players.Add(p3);

while(true) //infinite loop
{
    Player nextOne = players.Get(); // It will always get next player
}

I'm looking is a collection/list/buffer/array etc. that will have some kind of "Get" method, which return next item, always. And when it reach the end, it will return first item.

Great example would be a card game, like poker: I have list of players.. I always return next player, like in the circle.

My question is: is there already, somewhere in C#/.NET, such collection implemented? If not, is writing an extension method for List the best solution?

Lews Therin
  • 3,707
  • 2
  • 27
  • 53
  • It should be easy enough to build your own.... – rory.ap Oct 14 '15 at 16:10
  • 2
    Possible duplicate of [Creating a circularly linked list in C#?](http://stackoverflow.com/questions/716256/creating-a-circularly-linked-list-in-c) – James Thorpe Oct 14 '15 at 16:12
  • Don't bother with List, you just need to create an Ienumerable so that MoveNext wraps around. – Nathan Cooper Oct 14 '15 at 16:14
  • @JamesThorpe I'm not sure it is. That one is about Linked list and what's more important doesn't have Servy's answer - which is just perfect. I was looking for infinite loop. I guess I should edit the title, cause it's not accurate. I'll do it soon – Wayne Paterson Oct 14 '15 at 17:04

1 Answers1

6

You can us the following method to create a sequence that is the infinite repetition of another (presumably finite) sequence.

//TODO consider coming up with a better name
public static IEnumerable<T> IterateInfinitely<T>(
    this IEnumerable<T> sequence)
{
    while(true)
        foreach(var item in sequence)
            yield return item;
}

Using this you can now write:

foreach(var player in players.IterateInfinitely())
{
    //TODO do stuff 
}
Servy
  • 202,030
  • 26
  • 332
  • 449
  • 1
    @singsuyash Yes, it'll iterate infinitely. That's why the method is named `IterateInfinitely`. – Servy Oct 14 '15 at 16:48
  • @Servy I like a programmer who names their methods meaningfully. – Po-ta-toe Oct 14 '15 at 16:59
  • That's great answer, thanks! Although, can you explain how it works exactly (those 3 lines from while till yield)? I guess I need to read more about `yield` :/ – Wayne Paterson Oct 14 '15 at 16:59
  • `yield` at its best! Great solution to the problem – blogbydev Oct 14 '15 at 17:00
  • @singsuyash ahh, sorry but can you briefly explain what's happening in those three lines? I can't understand it actually – Wayne Paterson Oct 14 '15 at 18:40
  • @WaynePaterson You can fine lots of information on `yield` online, including in-depth explanations, tutorials, books, articles, examples, and so on. It's well beyond the scope of an SO comment to explain the entire feature. – Servy Oct 14 '15 at 18:47