How can I make an Observable Hashset in C#?

后端 未结 3 1542
轮回少年
轮回少年 2020-12-14 19:50

Currently I am using an ObservableCollection within a WPF application, the application is an implementation of Conway\'s Game of life and works well for about 500 cells but

3条回答
  •  无人及你
    2020-12-14 20:50

    I don't know if this will help, but here's a really simple implementation of an "observable set" that I made for a personal project. It essentially guards against inserting (or overwriting with) an item that is already in the collection.

    If you wanted to you could simply return out of the methods rather than throwing an exception.

    public class SetCollection : ObservableCollection 
    {
        protected override void InsertItem(int index, T item)
        {
            if (Contains(item)) throw new ItemExistsException(item);
    
            base.InsertItem(index, item);
        }
    
        protected override void SetItem(int index, T item)
        {
            int i = IndexOf(item);
            if (i >= 0 && i != index) throw new ItemExistsException(item);
    
            base.SetItem(index, item);
        }
    }
    

提交回复
热议问题