So, some quick search-binding list ... Here's the one I prepared earlier.
This is the sync / map approach you were talking about. I used this before for fast ticking data, where the main bottleneck was looking for items in the list. I believe that I have considered all the methods necessary for synchronization or "organization." You can add a test for AddRange - I don't have a decompiler, I'm not sure if it just calls InsertItem.
, , , , .
, , BindingList, , FastFind.
public class FastLookupBindingList<TKey, TVal> : BindingList<TVal>
{
private readonly IDictionary<TKey, TVal> _dict = new Dictionary<TKey, TVal>();
private readonly Func<TVal, TKey> _keyFunc;
public FastLookupBindingList(Func<TVal, TKey> keyFunc)
{
_keyFunc = keyFunc;
}
public FastLookupBindingList(Func<TVal, TKey> keyFunc, IList<TVal> sourceList) : base(sourceList)
{
_keyFunc = keyFunc;
foreach (var item in sourceList)
{
var key = _keyFunc(item);
_dict.Add(key, item);
}
}
public TVal FastFind(TKey key)
{
TVal val;
_dict.TryGetValue(key, out val);
return val;
}
protected override void InsertItem(int index, TVal val)
{
_dict.Add(_keyFunc(val), val);
base.InsertItem(index, val);
}
protected override void SetItem(int index, TVal val)
{
var key = _keyFunc(val);
_dict[key] = val;
base.SetItem(index, val);
}
protected override void RemoveItem(int index)
{
var item = this[index];
var key = _keyFunc(item);
_dict.Remove(key);
base.RemoveItem(index);
}
protected override void ClearItems()
{
_dict.Clear();
base.ClearItems();
}
}
:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
private void simpleButton1_Click(object sender, EventArgs e)
{
var keyedBindingList = new FastLookupBindingList<int, Person>(p => p.Id)
{
new Person {Id = 1, Name = "Joe"},
new Person {Id = 2, Name = "Josephine"}
};
var person = keyedBindingList.FastFind(2);
var unkonwn = keyedBindingList.FastFind(4);
}