I have a generic class for performing some filtering actions on ObservableCollections - a small custom pagination mechanism.
public class Paginate<T> : INotifyPropertyChanged
{
public readonly ObservableCollection<T> all_data;
public ObservableCollection<T> filtered_data;
public Paginate(ObservableCollection<T> _data)
{
all_data = _data;
filtered_data = all_data;
}
public ObservableCollection<T> Filter(Func<T, bool> obj)
{
//Filter collection
//This takes about 10ms to finish - no errors at all
//var test = all_data.Where(obj).ToList();
//This doesn't finish at all, consuming a lot of memory
filtered_data = all_data.Where(obj).ToObservableCollection();
//...
return filtered_data;
}
}
My problem is in Filter method, converting IEnumerable to ObservableCollection doesn't finish. However, when Linq result are small number of records It does finish correctly. Here is how I call everything in ViewModel (command for button):
private void Filter_Execute(object parameter)
{
//Test_data is ObservableCollection<Student>, _paginate is instance of Paginate class
Test_data = _paginate.Filter(Filter_data);
//...
}
public bool Filter_data(object obj)
{
//Filtering logic
if (obj is Student student)
{
return ((string.IsNullOrEmpty(Name) ? true : student.NAME == Name)
& (string.IsNullOrEmpty(Surname) ? true : student.SURNAME == Surname)
& (string.IsNullOrEmpty(Age) ? true : student.AGE == Convert.ToInt16(Age))
);
}
return false;
}
And my extension method for converting IEnumerable to ObservableCollection:
public static ObservableCollection<T> ToObservableCollection<T> (this IEnumerable<T> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return new ObservableCollection<T>(source);
}
So what am I doing wrong here ?
Update
My problem lies on UI side when binding to DataGrid. Obviously when Linq results exceeds number of items that you are displaying in UI you mustn't have property ScrollViewer.CanContentScroll set to False. This somehow causes huge memory leak that doesn't stop.
I'm working on a solution now.