2 using System.Collections.Generic;
19 ListSortDirection sortDirection;
20 PropertyDescriptor sortProperty;
24 Action<SortableBindingList<T>, List<T>>
25 populateBaseList = (a, b) => a.ResetItems(b);
29 static Dictionary<string, Func<List<T>, IEnumerable<T>>>
30 cachedOrderByExpressions =
new Dictionary<string, Func<List<T>,
35 originalList =
new List<T>();
40 originalList = enumerable.ToList();
41 populateBaseList(
this, originalList);
47 populateBaseList(
this, originalList);
51 ListSortDirection direction)
62 var orderByMethodName = sortDirection ==
63 ListSortDirection.Ascending ?
"OrderBy" :
"OrderByDescending";
64 var cacheKey = typeof(T).GUID + prop.Name + orderByMethodName;
66 if (!cachedOrderByExpressions.ContainsKey(cacheKey))
68 CreateOrderByMethod(prop, orderByMethodName, cacheKey);
71 ResetItems(cachedOrderByExpressions[cacheKey](originalList).ToList());
73 sortDirection = sortDirection == ListSortDirection.Ascending ?
74 ListSortDirection.Descending : ListSortDirection.Ascending;
78 private void CreateOrderByMethod(PropertyDescriptor prop,
79 string orderByMethodName,
string cacheKey)
87 var sourceParameter = Expression.Parameter(typeof(List<T>),
"source");
88 var lambdaParameter = Expression.Parameter(typeof(T),
"lambdaParameter");
89 var accesedMember = typeof(T).GetProperty(prop.Name);
90 var propertySelectorLambda =
91 Expression.Lambda(Expression.MakeMemberAccess(lambdaParameter,
92 accesedMember), lambdaParameter);
93 var orderByMethod = typeof(Enumerable).GetMethods()
94 .Where(a => a.Name == orderByMethodName &&
95 a.GetParameters().Length == 2)
97 .MakeGenericMethod(typeof(T), prop.PropertyType);
99 var orderByExpression = Expression.Lambda<Func<List<T>, IEnumerable<T>>>(
100 Expression.Call(orderByMethod,
101 new Expression[] { sourceParameter,
102 propertySelectorLambda }),
105 cachedOrderByExpressions.Add(cacheKey, orderByExpression.Compile());
110 ResetItems(originalList);
113 private void ResetItems(List<T> items)
118 for (
int i = 0; i < items.Count; i++)
120 base.InsertItem(i, items[i]);
124 protected override bool SupportsSortingCore
133 protected override ListSortDirection SortDirectionCore
137 return sortDirection;
141 protected override PropertyDescriptor SortPropertyCore
151 originalList = base.Items.ToList();
override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
Inherits BindingList and overrides the functions necessary to provide sorting. The code of this c...
override void RemoveSortCore()
override void OnListChanged(ListChangedEventArgs e)
SortableBindingList(List< T > list)
SortableBindingList(IEnumerable< T > enumerable)