开发者

Most efficient endless loop in C# (carousel)

开发者 https://www.devze.com 2023-02-05 07:28 出处:网络
Assuming a list of objects, each with an ID, what\'s the most efficient way of building a carousel, so that each object knows what its previous and next item is. The Last Item\'s previousId will link

Assuming a list of objects, each with an ID, what's the most efficient way of building a carousel, so that each object knows what its previous and next item is. The Last Item's previousId will link to the first item. The first item's previousId will link to the last.

I need the ID of the previous and the ID of the next, as this will be used to populate next and previous buttons on a web page.

I know I could iterate over them, adding placeholders for _next and _prev id, but what's the most efficient way to do this?

I figure my object should look like thi开发者_如何学Cs:

class Item {
    public int Id { get; set; }
    public string ItemName { get; set; }
    public int Next { get; set; }
    public int Prev { get; set; }
}

SO, if I have a List<Item> items how can I most efficiently add the previous and next IDs to each item?

    int _prev = items.LastOrDefault().id;
    int _next = items.Count > 1 ? items[1].id : _prev;
    foreach (var i in items) {
        i.prev = _prev;
        i.next = (_next < 
        _prev = i.id;
        //_next = ???
    }

I think I'm looking at this wrong way. Is there a better way of doing this?


If you don't want to use LinkedList and willing to use indexes instead of foreach as Marc Gravel suggested:

int count = items.Length;
for(int index = 0; index < count; index ++)
{
  item.Next = items[(index + 1) % count];
  item.Prev = items[(index - 1 + count) % count];
}


Use a LinkedList to hold your objects.

0

精彩评论

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