1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
public static class BindingListExtension
{
private static IBindingList internalList;
private static Dictionary<int, object> internalFilteredList;
private static bool hasChanged = true;
public static IEnumerable<T> View<T>(this BindingList<T> list, Func<T, bool> filter) where T: class
{
if (internalList != list)
{
Action Init = new Action(()=>
{
internalList = list;
internalFilteredList = new Dictionary<int, object>();
for (int i = 0; i < internalList.Count; i++)
{
var item = internalList[i];
if (filter(item as T))
internalFilteredList.Add(i, item);
}
});
Init();
internalList.ListChanged += new ListChangedEventHandler((s, e) =>
{
int i = e.NewIndex;
if (e.ListChangedType == ListChangedType.ItemDeleted)
internalFilteredList.Remove(i);
else if (e.ListChangedType == ListChangedType.ItemAdded)
internalFilteredList.Add(i, internalList[i]);
else if (e.ListChangedType == ListChangedType.Reset)
Init();
});
}
//return internalFilteredList.Values.Cast<T>();
foreach (var item in internalFilteredList.Values.Cast<T>())
yield return item;
}
private static BindingList<T> ToBindingList<T>(this IEnumerable<T> en)
{
BindingList<T> b = new BindingList<T>();
foreach (T item in en)
b.Add(item);
return b;
}
} |
Partager