Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a ObservableCollection by user input

Tags:

c#

silverlight

I have an ObservableCollection of about 1000 objects that needs to be filtered (searched) by the end user. The user must be able to search by name or employee id. The List Control consumes FilteredEmployees and Employees is loaded up with everything on page load.

I currently have it set up as such:

public ObservableCollection<EmployeeServicesData> Employees { get; set; }
public ObservableCollection<EmployeeServicesData> FilteredEmployees { get; set; }

internal void FilterEmployee(string searchText, bool isByName)
{
    if (searchText.Length > 0)
    {
        IEnumerabe<EmployeeServicesData> filter;

        if (isByName)
            filter = Employees.Where(x => x.Name.Length >= searchText.Length).Where(x => x.Name.Substring(0, searchText.Length) == searchText.ToUpper());
        else
            filter = Employees.Where(x => x.EmployeeNumber.ToString().Length > searchText.Length).Where(x => x.EmployeeNumber.ToString().Substring(0, searchText.Length) == text);

        foreach (EmployeeServicesData employee in filter)
            FilteredEmployees.Add(employee);
    }
}

Sanitation is handled before this method.

This doesn't smell very efficent. Should I use two methods for this, or is there a better way to handle filtering?

I'd like to keep Employees at an unchanged state so I can repopulate FilteredEmployees to the full list without hitting the DB again.

like image 215
Slipfish Avatar asked Sep 22 '09 15:09

Slipfish


1 Answers

I know this is an old post but I was using it to help me with the filtering aspect and noticed that SlipFish was creating the ObservableCollection by looping round the IEnumerable collection.

As the ObservableCollection constructor accepts an IEnumerable collection the ObservableCollection could be created like this:

FilteredEmployees = new ObservableCollection<EmployeeServicesData>(filter);
like image 196
EzaBlade Avatar answered Oct 14 '22 17:10

EzaBlade