Search code examples
c#wpfcollectionsobservablecollection

Display Items in observable collection as circular linked list


I have a Observable collection filled by items and a button, these items ordered descending by their ID

ocItems = new ObservableCollection<Item>();
IQueryable<Item> Query = _context.Item.OrderByDescending(s=>s.ItemID);
ocItems = new ObservableCollection<Item>(Query );

I want to display information for each item in each click in below way:

The first click display Item1 infomation, the secound click display the Item2 information .... The fifth click display the Item5 information, The sixth click display the Item1 information .. and so on.

How can I display Items in observable collection as circular linked list? when I display the second Item, how can I out the first item in the end of list?

Hope this clear


Solution

  • Simply reset your index operator value back to zero:

    using System;
    using System.Collections.ObjectModel;
    
    public class Program
    {
        public static void Main()
        {
            var items = new []
            {
                new Item{ Id = 1, Value = "Hello" },
                new Item{ Id = 2, Value = "World!" },
            };
    
            var collection = new ObservableCollection<Item>(items);
    
            for(int i = 0; i < 10; i++)
            {
                var item = collection[i % collection.Count];
                var message = String.Format("{0}: {1}", item.Id, item.Value);
                Console.WriteLine(message);
            }
        }
    }
    
    public class Item
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }